user2916607
user2916607

Reputation:

Copying files from a path with %~dp0% does not work

Note that I am wrong in assuming that I should use %~dp0% to get the path excluding the filename of a batch file from inside it. I am leaving the question as-is as I have seen others with the same faulty premise. See the accepted answer, and its comment, for more information.


As a lot of the more advanced Windows users' know the expression %~dp0% in a batch file will be evaluated to the batch file's directory including the trailing backslash.

If I have a batch file in D:\ containing echo %~dp0%, that line will behave as expected and output D:\.

The problem

If I create a file D:\FILETOCOPY.txt and a batch file D:\problem.bat with following contents:

@ECHO OFF

copy D:\FILETOCOPY.txt %userprofile%\FILECOPIEDA.txt

copy %~dp0%FILETOCOPY.txt %userprofile%\FILECOPIEDB.txt

set Evaluated=%~dp0%FILETOCOPY.txt
copy %Evaluated% %userprofile%\FILECOPIEDC.txt

cmd.exe

I get this output when I run it (by double clicking) on it:

        1 file(s) copied.
The system cannot find the path specified.
        1 file(s) copied.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

D:\>

And the file %userprofile%\FILECOPIEDB.txt is missing from the destination. It does work, as proven by FILECOPIEDC.txt, if I evaluate the %~dp0% on a separate line. It seems that it messes up the file copy somehow, but it works as expected in the middle of a echoed line.

Exactly what is going on here?

Upvotes: 2

Views: 11845

Answers (2)

foxidrive
foxidrive

Reputation: 41244

Two \\ in succession are treated as a single \ in Windows. It's not a problem.

If your %userprofile% contains spaces or & then surround the entire term in double quotes.

The other point has been mentioned - the term should be %~dp0

Upvotes: 3

Magoo
Magoo

Reputation: 80113

Try %~dp0 not %~dp0%.

Your command translates to (brackets and underscores inserted for clarity)

copy [%~dp0]_[%FILETOCOPY.txt %] userprofile_[%\FILECOPIEDB.txt]

and since the variable %FILETOCOPY.txt % does not exist, it will be replaced by an empty string.

Upvotes: 7

Related Questions