3

In a PowerShell script, I have to call a batch file in an elevated window. So I do

Start-Process my.bat -Verb runas

Now, my.bat expects to have some of the ENV variables I set on the original window. However, since the elevated window is executed as admin, those variables I set as a regular user don't appear to be set on the admin window.

Is there a way to set ENV vars in an admin window prior to calling my.bat?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
b3bel
  • 375
  • 1
  • 5
  • 15
  • Is it required that you make it run as admin using powershell? You could also make the batch script elevate itself. – Dennis van Gils Dec 14 '15 at 07:59
  • Possible duplicate of [Powershell: Setting an environment variable for a single command only](http://stackoverflow.com/questions/1420719/powershell-setting-an-environment-variable-for-a-single-command-only) – sodawillow Dec 14 '15 at 09:35

1 Answers1

3

What you want isn't possible. For security reasons elevated processes don't inherit the parent's environment. What you can do is create a wrapper script that you run elevated and have that script set the environment variables from parameters before running my.bat.

IIRC "runas" isn't enabled for PowerShell scripts by default, so the wrapper script would have to be a batch file:

@echo off

set "VARIABLE1=%1"
set "VARIABLE2=%2"

call "C:\path\to\my.bat"

Run it like this:

Start-Process .\wrapper.ps1 -ArgumentList 'foo', 'bar' -Verb runas
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328