Reputation: 539
I have two batch file on the C:\
drive and am using %~dp0
command to use the path of the first script to make a copy the second batch script:
COPY %~dp0"Hello World.BAT" C:\"Hello World.bak"
Early in the script I am required to change to a sub directory off the root of the C:\
but this stops the above copy command from working the error I get is "the file cannot be found". If I stay in the root of the C:\
the copy command works perfectly. Any ideas why this is happening.
Upvotes: 1
Views: 5491
Reputation: 706
Another way to solve this would be to save %~dp0 in another variable at the beginning of your script.
@echo off
setlocal
set filepath=%~dp0
.
.
some code
.
.
cd away from original path
.
.
COPY "%filepath%Hello World.BAT" "C:\Hello World.bak"
That should work.
I am tempted to think the reason it is not working has to do with your quotes.
You have this:
COPY %~dp0"Hello World.BAT" C:\"Hello World.bak"
replace it with this:
COPY "%~dp0Hello World.BAT" "C:\Hello World.bak"
you need to wrap the entire path in quotes to be sure it will work. If you have:
C:\Program Files\Somefolder\
as your path and use the quotes how you have them it will turn out like this:
"C:\Program Files\Somefolder\""Hello World.bak"
and it won't work.
Upvotes: 5
Reputation: 130879
I haven't exactly worked out in my mind how changing the current directory causes the command to fail when it works before the change. But I notice that the quotes are not placed optimally. Spaces in the path would cause the command to fail, though it seems to me it should fail regardless of your current directory.
I would use:
COPY "%~dp0Hello World.BAT" "C:\Hello World.bak"
Moving the quote to the front of the 1st argument is potentially important. Moving it for the 2nd argument is not important since there are obviously no spaces in the path, but it looks better to me.
edit
After reading your question more carefully, I'm thinking there must be more to the story. If both batch files are in the root of the C drive, then your original posted code should work.
Try editing your script to diagnose what is happening. Put ECHO before the copy command so you can see what the script is attempting to do. (or simply make sure echo is on, but then it may be harder to find the correct line in the output.)
echo COPY %~dp0"Hello World.BAT" C:\"Hello World.bak"
If you still can't figure out what is wrong, post the results so others might help.
Upvotes: 2