Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

%CD% variable behaviour differs when right click and use run as admin

I have a windows cmd file that is making use of the %CD% environment variable to determine the execution directory of the cmd file.

When I run the cmd file from the command line it works correctly, meaning that the %CD% variable contains the working directory. If I double left click the cmd it also works as I expect. However if I right click the cmd file and select runas administrator then the %CD% variable contains the value "C:\Windows\system32" not the curent directory where the cmd is executing.

I was able to reproduce the problem with the following script:

echo %CD%
pause
like image 695
Pedro Santos Avatar asked Jul 13 '10 13:07

Pedro Santos


People also ask

How do I open an environment variable as an administrator?

If you need to edit system environment variables, right click on the shortcut and select “Run as administrator” from the context menu.

How do I enable right click as administrator?

Right-click or press-and-hold on the shortcut, and then right-click or press-and-hold again on the program's name. Then, from the menu that opens, choose "Run as administrator." You can also use the "Ctrl + Shift + Click/Tap" shortcut on an app's taskbar shortcut to run it with administrator permissions in Windows 10.

How do I check Environment Variables in CMD?

To Check if an Environment Variable ExistsSelect Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable. For example, to check if NUKE_DISK_CACHE is set, enter echo %NUKE_DISK_CACHE%.

How do I change Environment Variables in Windows?

In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable. Click Edit to modify an existing environment variable.


2 Answers

Trying using %~dp0 instead of %cd%... this should give you the directory which contains the batch (NT shell) script was launched from in any case.

like image 116
ewall Avatar answered Oct 27 '22 00:10

ewall


Are you confusing working/current directory with the directory your batch file is in?

If I have a simple batch file with just

@echo off
echo %cd%

and this is stored in c:\foo\bar\test.cmd

In cmd I execute

cd c:\foo
bar\test

test.cmd will print c:\foo and not c:\foo\bar

I assume UAC uses system32 since it is possible to elevate with a different user and that user might not have access to whatever the current directory is.

If you want the directory your batch file is in, use %~dp0, if you want the current directory, use . or %CD%

like image 39
Anders Avatar answered Oct 26 '22 23:10

Anders