Reputation: 20354
A batch file on Windows (XP and later) needs to know the name of the directory it's located in. Only the folder name, not the whole path and not the batch file name itself.
So the file stored in C:\temp\abc\script.cmd should get the name "abc" in a variable.
How can that be done?
The usual parameter extensions like %~p0
can only extract the entire path (\temp\abc\ ) and they only work on real parameters (%0, %1, %2...) not on other variables, so they cannot be stacked or combined. So they're too limited for this task. The for
command can only address tokens at a defined position from the start, not the "last" or second-last token.
For simplicity of execution and portability, it must be a batch file (.cmd), not PowerShell.
Upvotes: 3
Views: 5239
Reputation: 130819
Any time you have the full path to a file, you can simply append \..
and use a FOR loop with the correct modifiers to get the parent folder name.
for %%A in ("%~f0\..") do set "myFolder=%%~nxA"
Upvotes: 9