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
If you need to edit system environment variables, right click on the shortcut and select “Run as administrator” from the context menu.
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.
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%.
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.
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.
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%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With