Call a BAT in an elevated window and changing ENV variables before

谁说胖子不能爱 提交于 2019-12-02 01:19:50

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34261567/call-a-bat-in-an-elevated-window-and-changing-env-variables-before

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!