Here's one way to retrieve the name of the folder containing a file accessed by a CMD command. Using the OP's example of a file with path C:\test\pack\a.txt
you would want your command to pull out that last folder name, "pack." (As dgnuff noted in a comment, the highest-scoring answer currently is an answer to a different question, and it won't help if you're in the OP's situation.)
The way I'm doing it is with nested FOR loops. Here's an example, as the command would appear in a batch file rather than entered directly on the command line:
FOR %%Z in ("*.txt") do (FOR %%I in ("%%~dpZ.") do (copy "%%~Z" "%%~dpZ%%~nxI.archive\%%~nxZ" ))
This example bach file command copies text files to a subfolder named after the folder with the files:
C:\test\pack\a.txt -> C:\test\pack\pack.archive\a.txt
C:\test\pick\b.txt -> C:\test\pick\pick.archive\b.txt
E:\A\B\C\D\foo.txt -> E:\A\B\C\D\D.archive\foo.txt
The outer FOR loop copies the files. But you need the inner FOR loop to build the destination path, since the destination subfolder name is based on the name of the source folder. The sequence "%%~dpZ."
— with that dot after the Z — retrieves the name of the folder containing the current file, which can then be referenced via the parameter I
(whereas Z
is the reference to the file being copied). See the "Parameter Extensions" section on this page for review of the built-in variables used to build paths, as in "%%~dpZ%%~nxI.archive\%%~nxZ"