Get the name of the parent folder of the currently executing script batch

The batch file on Windows (XP and later) needs to know the name of the directory where it resides. Only the folder name, not the entire path, not the name of the batch file itself.

So the file stored in C: \ temp \ abc \ script.cmd should be given the variable name "abc" in the variable.

How can I do that?

Regular parameter extensions such as %~p0

can fetch the entire path (\ temp \ abc \) and they only work on real parameters (% 0,% 1,% 2 ...), not other variables, so they cannot be stacked or combined. Therefore, they are too limited for this task. The command for

can only address tokens in a certain position from the very beginning, not the "last" or second last token.

For ease of execution and portability, this should be a batch file (.cmd), not PowerShell.

+3


source to share


1 answer


If you have the full path to the file, you can simply add \..

and use a FOR loop with the correct modifiers to get the name of the parent folder.



for %%A in ("%~f0\..") do set "myFolder=%%~nxA"

      

+8


source







All Articles