MensSana
MensSana

Reputation: 580

How to use ~dp0 in a batch block on Windows 10

This seems like a bug to me...
I'm looking for an explanation or a pretty workaround...

When the script is located with a part ending with a closing parenthesis ) as in Program Files(x86), the script seems to "eat" the closing parenthesis.
Not happening on Windows 7, just on Windows 10...

@echo off
echo %%~dp0 outside the code block = %~dp0
if 0 EQU 0 (
    echo %%~dp0  inside the code block = %~dp0
)

You can try it with the script located in:

 - C:\Program Files (x86)\
 - C:\Program Files (x86)\Some Folder\
 - C:\Program Files (x86)\Some Folder\Another one\
 - C:\test-ok\test-not-ok-(1)\

Upvotes: 1

Views: 1120

Answers (1)

aschipfl
aschipfl

Reputation: 34949

This happens because the immediate %-expansion occurs before special characters like parentheses are recognised.

To prevent that you could quote the string, so special characters are protected:

@echo off
echo %%~dp0 outside the code block = "%~dp0"
if 0 EQU 0 (
    echo %%~dp0  inside the code block = "%~dp0"
)

Of course the quotation mark might disturb. But you could use delayed expansion to echo the path unquoted:

@echo off
set "string=%~dp0"
setlocal EnableDelayedExpansion
echo %%~dp0 outside the code block = !string!
if 0 EQU 0 (
    echo %%~dp0  inside the code block = !string!
)
endlocal

Alternatively you could use a for loop to achieve another expansion phase after special character recognition:

@echo off
for %%I in ("%~dp0") do (
    echo %%~dp0 outside the code block = %%~I
    if 0 EQU 0 (
        echo %%~dp0  inside the code block = %%~I
    )
)

Upvotes: 4

Related Questions