在powershell脚本中,是使用提升的权限运行另一个PowerShell脚本的调用:
try{
powershell -ExecutionPolicy Bypass -Command "Start-Process Powershell -Verb RunAs -Wait -ErrorAction Ignore -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File `"path\to\file`"'"
}
catch{
# I can't get to here - thats my problem!
}
字符串
然后,Windows提示符会询问您:“是否允许此应用更改您的设备?"。接受时,脚本将以提升的权限运行,但如果用户在此提示符中取消,则会发生错误。但在后一种情况下,我无法捕获取消。它只是给出一个错误,然后继续脚本。
有没有什么方法可以捕捉到错误(在try/catch块中),用户何时取消?在这里,我把-errorAction Ignore放在了Start-Process中,但是无论我选择什么errorAction,我都不能捕获错误。我还尝试在调用的第一部分添加errorAction(powershell -ExecutionPolicy Bypass -errorAction Ignore...)导致另一个未捕获的错误。您不能在此处使用errorAction...
如果用户取消Windows提示符,您是否知道如何使用提升的权限调用此脚本并捕获?
1条答案
按热度按时间8yoxcaq71#
对 * 外部程序 * 的调用 * 不 * 与PowerShell的错误处理系统集成, 在 Windows PowerShell 和PowerShell (Core) * 中总是 ,最高版本为7.3.x,* 默认情况下 * 在 v7.4+ 中,因此您不能将
try
/catch
与外部程序(如powershell.exe
)的调用一起使用。$LASTEXITCODE
变量手动测试失败:按照惯例,* 非零 * 值表示失败,您可以相应地采取行动。powershell.exe
**(Windows PowerShell CLI)调用。Start-Process
*-Verb RunAs
进行CLI调用 * 以实现提升-您可以自由选择CLI可执行文件,即您可以选择调用pwsh.exe
,PowerShell(核心)CLI。(Get-Process -Id $PID).Path
字符串