从具有特权提升的批处理文件运行Powershell脚本? [英] Run a Powershell script from Batch file with elevated privileges?
问题描述
我想从code.bat
我意识到start
命令会运行它,但要求它以admin身份运行,我该怎么做?
I realize that the start
command would run it but require that it be run as admin, how can I do this?
推荐答案
在您的批处理文件中:
powershell -Command "&{ Start-Process powershell -ArgumentList '-File C:\folder\psfile.ps1' -Verb RunAs}"
...基本上,您是在使用Powershell来运行Powershell.第二个实例提升为Admin,并使用这些权限运行脚本.
...basically you're using Powershell to run Powershell. The second instance is elevated to Admin and is running your script with those permissions.
完整说明:
Start-Process
可用于运行程序,并具有参数-Verb RunAs
,可将程序提升为以Admin身份运行.
Start-Process
can be used to run a program, and also has the parameter -Verb RunAs
which elevates the program to run as Admin.
我们无法从批处理文件调用Start-Process
,因为它是PowerShell命令.
We can't call Start-Process
from a batch file as it's a PowerShell command.
但是我们可以从批处理文件运行powershell
,然后使用-command
参数运行Start-Process
.
But we can run powershell
from a batch file, then using the -command
parameter to run Start-Process
.
我们再次使用Start-Process
运行powershell
并在脚本升格为Admin时运行您的脚本:-ArgumentList '-File C:\folder\psfile.ps1' -Verb RunAs
We use Start-Process
to run powershell
(again) and run your script when it is elevated to Admin: -ArgumentList '-File C:\folder\psfile.ps1' -Verb RunAs
这篇关于从具有特权提升的批处理文件运行Powershell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!