Passing a string parameter as a runtime Argument - batch-file

I want to open the particular path through the batch file. And I want to pass one node in path at run time. If I give input Google, I want to pass the string argument here. It will open the path
want to pass one node in path at run time . if i give input Google.i
want to pass the string argument here. it will open the path
C:\Program Files (x86)\google\Common
How can I achieve this?
My batch file:
#echo off
echo test variables
set input =
set /p input ="Choice"
echo C:\Program Files (x86)\%input%\Common
cd C:\Program Files (x86)\"%input%"\Common
pause

There are the following issues in your code:
there is a SPACE between the variable name and the = sign at the set commands, so it becomes a part of the variable name; hence the variable input remains empty/undefined;
there are quotes within the path at the cd command, which are forbidden characters there;
Here is the corrected version:
#echo off
echo test variables
set "input="
set /p "input=Choice"
echo "C:\Program Files (x86)\%input%\Common"
cd "C:\Program Files (x86)\%input%\Common"
pause
I put quotes around the path at the cd command. Although not necessary for cd, many other commands cannot handle paths containing spaces if the "" are missing.
To use the first command line argument instead of user input, remove the set commands and replace %input% by %~1. The ~ ensures that any surrounding quotes are removed. Type call /? in the command prompt for details on this.

Are you saying you want to run your batch file like this.
C:\>mybatch.bat Google
If so then your batch file just changes to this.
#echo off
echo test variables
echo C:\Program Files (x86)\%1\Common
cd C:\Program Files (x86)\%1\Common
pause

Related

Pass parameter in bat file to run from desktop short cut

I want to run a bat file from a desktop shortcut and pass a parameter to it.
I can run it from DOS with no problem.
When I try to run it from a desktop shortcut, I can enter the parameter, but it does not get passed.
I enter a file name like 20200103.txt and the bat file takes the .txt extension off so that only the first part of the file is used later in the bat file
Here are the first couple lines that I am using in the bat file
SET /I %1 DTE = %1
set %~n1 = %1%
ECHO %1
ECHO %1%
ECHO %~n1%
Is there any way to include a document when I submit a question?
When you are passing an argument for a file in a shortcut, you need to surround it with "" so if you want to pass 20200103.txt as arg 1 to the batch file you would put in the shortcut path\thing\thing\file "20200103.txt". Also, your code may not be working properly because /I is not an option is the "set" command. Like compo said, try checking out set /?

how to make batch file handle spaces in file names

I have the following batch file to make git diff invoke spreadsheet compare UI in windows. So I'm trying to pass the git diff's 2nd (old file) and 5th (new file) arguments to spreadsheet compare in order to make it compare the file using git diff.
So now, this batch file only successfully handles files with NO spaces in the file names, it CANNOT handle files with spaces in the file names.
What code should I add to this script to make this batch code handles file with spaces:
#ECHO OFF
set path2=%5
set path2=%path2:/=\%
ECHO %2 > tmp.txt
dir %path2% /B /S >> tmp.txt
C:/"Program Files"/"Microsoft Office"/root/vfs/ProgramFilesX86/"Microsoft Office"/Office16/DCF/SPREADSHEETCOMPARE.EXE tmp.txt
It currently throw errors like this:
Unhandled Exception: System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
at System.IO.Path.GetFileName(String path)
at ProdianceExcelCompare.Form1.StatusReady()
at ProdianceExcelCompare.Form1.Init()
at ProdianceExcelCompare.Form1..ctor(String instructionFile)
at ProdianceExcelCompare.Program.Main(String[] args)
fatal: external diff died, stopping at London comparison.xlsx
See the following answers on Stack Overflow:
How to set environment variables with spaces?
Why is no string output with 'echo %var%' after using 'set var = text' on command line?
They explain the recommended syntax set "VariableName=variable value" to define an environment variable and the reasons recommending this syntax.
Why does ECHO command print some extra trailing space into the file?
It explains why the space character left to redirection operator > on an ECHO command line is also written into the file as trailing space and how to avoid this safely on variable text written into the file.
See also Microsoft documentation about Using command redirection operators.
On other command lines than ECHO a space left to > is usually no problem.
It is in general wrong to use multiple times " within an argument string like a file or folder path. There should be just one " at beginning and one " at end. This is explained by help of Windows command processor output on last help page on running in a command prompt window cmd /?.
The Microsoft documentation about Naming Files, Paths, and Namespaces explains that the directory separator on Windows is \ and not / and therefore / should not be used in batch files on Windows in file/folder paths.
The help output on running in a command prompt window call /? explains how the arguments of a batch file can be referenced with which modifiers.
The code rewritten according to information posted above and on the referenced pages:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "path2=%~5"
set "path2=%path2:/=\%"
>"tmp.txt" echo %2
dir "%path2%" /B /S >>"tmp.txt" 2>nul
"%ProgramFiles%\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft Office\Office16\DCF\SPREADSHEETCOMPARE.EXE" "tmp.txt"
endlocal
The first line in tmp.txt contains the second argument as passed to the batch file, i.e. without or with surrounding double quotes.
The following code is necessary to write the second argument safely always without " into file tmp.txt even on second argument passed to the batch file is "Hello & welcome!":
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "path2=%~5"
set "path2=%path2:/=\%"
set "Argument2=%~2"
setlocal EnableDelayedExpansion
echo !Argument2!>"tmp.txt"
endlocal
dir "%path2%" /B /S >>"tmp.txt" 2>nul
"%ProgramFiles%\Microsoft Office\root\vfs\ProgramFilesX86\Microsoft Office\Office16\DCF\SPREADSHEETCOMPARE.EXE" "tmp.txt"
endlocal
>tmp.txt echo %~2 cannot be used as not working for something like "Hello & welcome!". Windows command processor would interpret the first string separated by normal space, horizontal tab, comma, equal sign, or no-break space (in OEM code pages) delimited string after & as command or application to execute as described by single line with multiple commands using Windows batch file.
"tmp.txt" could be written everywhere in both batch files also with just tmp.txt. But it is never wrong to enclose the complete file/folder argument string in double quotes even on not being really necessary because of the string does not contain a space or one of these characters &()[]{}^=;!'+,`~. So it is good practice to always enclose a complete file/folder argument string in double quotes. For example running a replace on both batch files searching for tmp.txt and using as replace string %TEMP%\%~n0.tmp would result in using instead of tmp.txt in current directory a temporary file with name of batch file as file name and file extension .tmp in directory for temporary files independent on what is the name of the batch file and what is the path of the directory for temporary files.
The last suggestion is reading this answer for details about the commands SETLOCAL and ENDLOCAL.
The temporary file should be also deleted finally before reaching an exit point for batch file execution.
You can use quotes as below:
It treats the string in quotes as a title of the new command window. So, you may do the following:
start "" "yourpath"
Found it in the below link :
https://ccm.net/forum/affich-16973-open-a-file-with-spaces-from-batch-file

%~1 and %1 Automatically Removing Everything after the first Space

So I am creating a batch file to store a selected folder's path into a text file to refer to it later on using another batch script...
I created registry entries to include a right-click context menu for any folder which triggers this specific batch file.
Basically When you right click a folder and click "Send to Script" it is supposed to copy the whole path / location of the right clicked folder.
To do so I am using the following command:
SET TargetDir=%~1
I also tried using %1and I also tried using the following code with delimiters
FOR /f "delims=;" %%a in ("%~1") do (
#echo %%a
)
The problem is that CMD is automatically trimming everything after the first space and since this is a path I am copying, I want to keep all the spaces and the path as is
Ex. If I use the command on a Folder such as "C:/folder/subfolder" the copyng is done correctly But If I use the command on a Folder such as "C:/folder/sub folder" the copying is done incorrectly and will only give me "C:/folder/sub" removing all the rest found after the first space detected.
Registry Entries
[HKEY_CLASSES_ROOT\Directory\shell\send-to-script]
"MUIVerb"="Send To Script"
"SubCommands"="sendscript"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\sendscript]
#="Send To Script"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\sendscript\command]
#="C:\\scripts\\pathtotext.bat %1"
Thanks for your help
You should change your registry key [...\sendscript\command] to
#="C:\\temp\\blob.bat \"%1\""
And in your batch you should use
REM The DisableDelayedExpansion is for preserve "!" in path names
setlocal DisableDelayedExpansion
SET "TargetDir=%~1"
setlocal EnableDelayedExpansion
(
echo target is !TargetDir!
) > C:\scripts\target.log
if "reseverdFolder" == "!TargetDir!" echo This folder is reserved
The batch file is not correct registered. For example look with regedit on value of registry key:
HKEY_CLASSES_ROOT\rtffile\shell\open\command
The value is displayed as:
"%ProgramFiles%\Windows NT\Accessories\WORDPAD.EXE" "%1"
So there are two arguments which are both enclosed in double quotes:
Argument 0 is the application to run with full path, file name and file extension enclosed in double quotes as path contains a space character.
Argument 1 is the name of the RTF file referenced with %1 passed by Windows Explorer with fullĀ path, file name and file extension which of course can also contain a space or any of the characters &()[]{}^=;!'+,`~ which require also enclosing entire argument in double quotes as output by cmd.exe on running it in a command prompt window with cmd /? on last help page.
So you need in your *.reg file used to import into Windows registry:
#="\"C:\\scripts\\pathtotext.bat\" \"%1\""
This string value is displayed in registry editor as:
"C:\scripts\pathtotext.bat" "%1"
And then you can use %1 or %~1 in your batch file as explained by help of command CALL output on running in a command prompt window on execution of call /?.
SET "TargetDir=%*"
Since the parameter apparently being supplied is C:\folder\sub folder then %~1 selects only the first supplied parameter of what cmd sees as two parameters.
%* means "the whole tail"
and echoing %* should show you exactly what cmd is seeing.

Making a directory on a path stored inside a variable in batch file

I'm new in batch programming. The thing is I have a path and a new folder name in 2 variables, so I want to concatenate it and make a new folder in that result path. I tried many things but nothing worked. Please help
I tried this code
#echo off
setlocal EnableDelayedExpansion
set ver=project
set spath=d:\a\svn\
set path=!%spath%%ver%!
mkdir %path%
pause
endlocal
Do not use path as name for an environment variable because such an environment variable is defined already by default with a very important meaning, see the answers on What is the reason forĀ 'sort' is not recognized as an internal or external command, operable program or batch file?
To concatenate two environment variable values just reference those two environment variables on assigning the value to one of the two environment variables or a new environment variable.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "ProjectVersion=project"
set "SvnPath=d:\a\svn\"
set "ProjectPath=%SvnPath%%ProjectVersion%"
mkdir "%ProjectPath%"
pause
endlocal
See also answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? for the reason using set "variable=value" with double quotes around string value to variable assignment, i.e. around the argument string of command SET.
The commands SETLOCAL and ENDLOCAL would not be really necessary here.
Possible would be also:
#echo off
set "ProjectVersion=project"
set "SvnPath=d:\a\svn\"
set "ProjectPath=%SvnPath%%ProjectVersion%"
mkdir "%ProjectPath%" 2>nul
if not exist "%ProjectPath%\" echo Failed to create directory "%ProjectPath%" & pause & goto :EOF
The batch file above creates the directory with suppressing any error message by redirecting STDERR to device NUL. An error message is output if the directory already exists or it was not possible to create the directory because NTFS permissions denies folder creation for current user or in directory path there is a file with the name of a directory in path, e.g. there is a file with name project in directory d:\a\svn or there is a file svn in directory d:\a. The next command with a backslash appended to directory path checks if the directory exists after execution of command MKDIR and outputs an error message with PAUSE and next exiting batch file when the directory still does not exist.
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and Single line with multiple commands using Windows batch file for an explanation of & operator.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
goto /?
if /?
mkdir /?
pause /?
set /?
setlocal /?
#echo off
setlocal EnableDelayedExpansion
set version=project
set spath=d:\a\svn\
set mypath=%spath%%version%
mkdir %mypath%
pause
endlocal
path is a reserved name - it defines the sequence of directories that is searched for an executable if the executable is not found in the current directory. If you change it, well - in short, gloom
ver is not a reserved name, but it is the name of a inbuilt utility and makes a poor choice for variable-name.
Your code was attempting to set your desired new pathname to the contents of the variable d:\a\svn\project. Since this variable is very unlikely to exist, you would have attempted to make a directory named nothing.
btw - there is no need to set mypath - md %spath%%ver% would work just as well. MD is a synonym of mkdir and is used more often.

batch - differentiating between a file and a path?

#echo off
set /p UserInput= What file would you like to hide?
cd %UserInput%
So I want to make a batch file that when run asks the user for a file, which it will hide in a maze of random folders. Let me explain.
Let's say I type C:\Program Files\Steam\butts.exe
It'd make a new directory in C:\Program Files\Steam
This is where I'm stuck. How do I have it find C:\Program Files\Steam from C:\Program Files\Steam\butts.exe?
Hah! The quickest and hacksiest way would be just to add a \.. to the end. For instance, on my desktop I have a file called weather.xml. If I do this:
dir c:\users\me\Desktop\weather.xml\..
... I end up with a directory listing of my Desktop. :)
So you can accomplish what you need with
cd %UserInput%\..
Otherwise, you could pass the path to a for loop or call :label to a subroutine to end up with %%~dpX. See the last couple of pages of help for and help call for details.
If you want to be even hacksier, instead of requiring the user to enter the path\to\file to set %UserInput%, you can use powershell to launch a File... Open sort of file chooser. See this answer for details.
Try this:
#echo off&setlocal
for %%i in ("C:\Program Files\Steam\butts.exe") do set "steampath=%%~dpi"
:: remove last backslash
echo %steampath:~0,-1%
You can use this batch
#echo off
set /p UserInput=What file would you like to hide?
for %%i in ("%UserInput%") do set path="%%~dpi"
cd %path%

Resources