Windows PowerShell Home
Windows shell bug with how %~dp0 is resolved
10/28/2010 12:46:55 PM
User(s) can reproduce this bug
Windows 7 64-bit Enterprise Edition
When running a .cmd or .bat script and using %~f0 or %~dp0 to resolve the batch script name if the batch script name has spaces (ex: "my script.cmd") and you chdir within the script then further references to %~dp0 will incorrectly resolve to the new cwd instead of the correct batch script location.
This does not happen if the script name has no spaces in it.
Example script below:
@REM When this script is named "test.cmd" (no spaces) it works as expected for the value of %~f0
@REM When this script is named "test with spaces.cmd" it does not work
echo "Stage 1: dp0 == %~dp0"
echo "Stage 2: dp0 == %~dp0"
echo Should have gotten value %STAGE1%
How often does this happen?
Have you seen this problem before in this product?
No, this is new to the most recent version
Run the following script using a filename with spaces like "test with spaces.cmd"
%~dp0 should still resolve to the folder the script is located in and not the sub-folder.
to post a comment.
Please enter a comment.
on 3/17/2012 at 8:15 AM
I would expect %~dp0 to always return the Drive\Path\ of folder containing the running script. As stated in the post, I observed it returns the Current Directory once it's been CD'd to in the script, IF the script name contains spaces and otherwise returns the correct value.
However, the Details of this post specify "Windows 7 x64" and that "this is new to most recent version". Whereas, I've just run it in XP SP3 x86 (32-bit) and it behaves the same in both cases.
to post a workaround.
Please enter a workaround.
© 2014 Microsoft