batch file deal with Ampersand (&) in folder name

后端 未结 3 1436
野的像风
野的像风 2021-01-06 14:48

Batch file below:

@echo off
set filelocation=C:\\Users\\myself\\Documents\\This&That
cd %filelocation%
echo %filelocation%
pause

give

3条回答
  •  死守一世寂寞
    2021-01-06 14:56

    Unlike Jeb, I don't think you need delayed expansion to use the variable in a safe way. Proper quotation could suffice for most use:

    @echo off
    SETLOCAL EnableExtensions DisableDelayedExpansion
    set "filelocation=C:\Users\myself\Documents\This&That"
    cd "%filelocation%"
    echo "%filelocation%"
    rem more examples:
    dir /B "%filelocation%\*.doc"
    cd
    echo "%CD%"
    md "%filelocation%\sub&folder"
    set "otherlocation=%filelocation:&=!%" this gives expected result
    
    
    SETLOCAL EnableDelayedExpansion
    set "otherlocation=%filelocation:&=!%" this gives unexpected result
    ENDLOCAL
    pause
    

    Moreover, this is universal solution while delayed expansion could fail in case of ! exclamation mark in processed string (e.g. last set command above).

提交回复
热议问题