Batch file working differently if ran in administr

2019-07-07 17:06发布

问题:

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

回答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.

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



回答2:

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.