on my Windows laptop my company sets the environment variable CD to some directory and I can not change that. In a batch file I have to use the current working directory like
set current_dir=%cd%
Now the environment overrides the current directory. If I put the line
set cd=
in front the original variable would be deleted. Is there a safe way to get the current directory as the batch file might be used in other environments too?
The first thing I'd suggest, for general use, as per my comment, is that you use %__CD__%
, (or if you do not want the trailing backward slash, %__CD__:~,-1%
), instead.
Example:
@Set "CWD=%__CD__:~,-1%"
@Set CWD 2>NUL
@Pause
The following alternatives may also help you out, although none are tested within a similarly broken environment:
@Set "CWD="
@For %%G In (.) Do @Set "CWD=%%~fG"
@Set CWD 2>NUL
@Pause
@Set "CWD="
@For /F "Delims=" %%G In ('CD') Do @Set "CWD=%%G"
@Set CWD 2>NUL
@Pause
@Set "CWD="
@For /F "EOL=? Delims=" %%G In ('Echo Prompt $P^|%SystemRoot%\System32\cmd.exe /D/E')Do @Set "CWD=%%G"
@Set CWD 2>NUL
@Pause