Asheara
Asheara

Reputation: 73

Batch file working differently if ran in administrator mode

I've been trying to create batch file for converting files in a directory. The directory is being given via this code:

@echo off

rem // setting input directory
:input1
set/p "inputdir=Input directory: "

rem // if input is invalid, prompt again
if not exist "%inputdir%" (
echo Directory does not exist.
echo "%inputdir%"
goto input1 
) 

It works well - normally. However, because I've considered using environmental variables later on, I also tried running it as administrator. However - the problem is, that when i run it normally, it takes the directory, script continues without a problem. When I run in administrator more, it acts as "Directory does not exist"

It works normally for locations on C: and D: drives, this issue comes up for O: and P: drives, which are made by subst.

Any idea how to solve this problem? Thank you

Upvotes: 2

Views: 467

Answers (3)

NullaNulla
NullaNulla

Reputation: 1

"Normal and elevated ("run as administrator") processes do not share drive mappings (by default) or substd drives. If you run a process in an elevated context, you'll have to map the drives there or map them in an elevated context (e.g. run cmd.exe as an administrator) before you attempt to start the target script."

THANK YOU!!!!

I've been frustrated for 3 days now with constant resets etc trying to work out why when I map Z: in some cases explorer won't see it and why my script that needs elevated has been ACTING why it hasn't been running any commands in the if exists z:\blah ... so again thank you for breaking my 3 day frustration.

What's worse is I sort out assist from MS for this one and they were stumped too.

Upvotes: 0

Todd Hartman
Todd Hartman

Reputation: 90

Normal and elevated ("run as administrator") processes do not share drive mappings (by default) or substd drives. If you run a process in an elevated context, you'll have to map the drives there or map them in an elevated context (e.g. run cmd.exe as an administrator) before you attempt to start the target script.

Reference: Some Programs Cannot Access Network Locations When UAC Is Enabled

Upvotes: 3

RGuggisberg
RGuggisberg

Reputation: 4750

When you 'Run as administrator' the current directory is not what you think! Just add these lines to the beginning of your bat file to prove it to yourself:

@echo off
echo(CD=%CD%
pushd %~dp0
echo(CD=%CD%
pause

So what you need to do is add this line to your bat file BEFORE you reference any files/folders I typically put it near the beginning.

pushd %~dp0

This will also work properly when you run from a mapped network drive.

Upvotes: 1

Related Questions