Batch file - Current working directory interferes with environment variable CD

505 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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
4
On

The basic command to assign the current path to a variable is this:

Command line: FOR /f %p in ('CD') do SET myVar=%p
Batch script: FOR /f %%p in ('CD') do SET myVar=%%p

But you can go further and edit the Windows registry
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]\autoron
by inserting the following macro every time you open an instance of MSDOS:

DOSKEY CHDIR=(IF [$1] == [] ( CD ) ELSE ( PUSHD $* )) & FOR /f %p in ('CD') do @SET cd=%p

Thus, overriding the CHDIR command to set the current path to the %cd% variable or whatever else you want. Also working with network directories :D