Pass path with spaces as parameter to bat file

kjv picture kjv · Jan 23, 2009 · Viewed 193.3k times · Source

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>

Answer

zikaS picture zikaS · Dec 8, 2010

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"