Within my batch file I have a variable that contains a file path:
SET VAR1=C:\Folder1\Folder2\File.txt
I would like to extract on the directory structure and retreive:
C:\Folder1\Folder2\
I have read threads like this where I need to use %~dp0 where 0 I believe is passed as a parameter. I have tried %~dpVAR1 but that doesn’t work. How can I get the output I’m looking for, but with a variable containing the file path?
Also, to make matters difficult, I have to perform all of this within an IF condition which means that once the variable is declared, I will need to refer to it with ! instead of % (I have declared setlocal enableextensions enabledelayedexpansion at the beginning of my script to allow for this).
Any help is much appreciated!
Thanks!
Andrew
You are attempting to use parameter expansion syntax on an environment variable – that cannot work. But it is relatively easy to do what you want.
Using a CALL (relatively slow):
Using FOR, assuming the variable does not contain any wildcards (fast)
Using FOR, if the variable may contain wildcards (also fast)
Note 1: If the variable does not contain the full path, then all the solutions will attempt to resolve the name into an absolute path and will return the full absolute path. For example, if var contains
foobar\test.txt, then the solutions will include the full path to the current directory, even if the file is not found. Something likec:\pathToCurrentDirectory\foobar\.Note 2: All solutions above will remove all quotes from the path.
Note 3: A path could include the
!character, which will cause problems when expanding%~dp1or%%~dpFbecause you have delayed expansion enabled. The delayed expansion will corrupt both^and!if the value contains!. There is a solution that involves protecting both!and^. Here is a demonstration applied to the last solution above. The protection requires normal expansion, and since you are within a code block, it requires at least one CALL. It could be done without a subroutine, but it is easier with a subroutine. The subroutine assumes the variable is namedvar.