Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass path with spaces as parameter to bat file

I have a simple bat script that copies files from an known directory to a directory given by the user. How can I pass the path (it might contain spaces) to my script and use it with the xcopy command?


In my code i have the following

:READ_PWA_PATH     if "%1" == "" (          rem Set default path         set PWA_PATH="C:\Program Files\PWA"         rem         echo You have not specified your PWA url.         echo Default will be assumed: C:\Program Files\PWA.          choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"             IF ERRORLEVEL ==2 GOTO CANCEL             IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH         GOTO END     ) else (         set PWA_PATH=%1     ) 

If I simply call the script I get the following error:

C:\Projects\Setup>install.cmd "C:\program files (x86)"  ----------------- SETUP SCRIPT -----------------  files was unexpected at this time. C:\Projects\Setup> 
like image 926
kjv Avatar asked Jan 23 '09 14:01

kjv


People also ask

How do you handle a space in a batch file?

When you send arguments, those with poison or space characters need to be doublequoted. Inside your batch file, if you no longer need the surrounding doublequotes, you'd remove them by using %~5 instead of %5 . Additionally the recommended syntax for the set command is Set "VariableName=VariableValue" .

How do you write a file path with spaces?

Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified.

What is %% in a batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.


1 Answers

Use "%~1". %~1 alone removes surrounding quotes. However since you can't know whether the input parameter %1 has quotes or not, you should ensure by "%~1" that they are added for sure. This is especially helpful when concatenating variables, e.g. convert.exe "%~1.input" "%~1.output"

like image 140
zikaS Avatar answered Sep 19 '22 10:09

zikaS