检测用户是否取消调用powershell中的提升提示符

zbdgwd5y  于 4个月前  发布在  Shell
关注(0)|答案(1)|浏览(48)

在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提示符,您是否知道如何使用提升的权限调用此脚本并捕获?

8yoxcaq7

8yoxcaq71#

对 * 外部程序 * 的调用 * 不 * 与PowerShell的错误处理系统集成,Windows PowerShellPowerShell (Core) * 中总是 ,最高版本为7.3.x,* 默认情况下 * 在 v7.4+ 中,因此您不能将try / catch与外部程序(如powershell.exe)的调用一起使用。

  • 相反,您必须通过自动$LASTEXITCODE变量手动测试失败:按照惯例,* 非零 * 值表示失败,您可以相应地采取行动。
  • 详情请参见this answer
  • 但是,*鉴于您是从PowerShell 调用 *,因此无需通过powershell.exe**(Windows PowerShell CLI)调用。
  • 也就是说,除非您运行 PowerShell(核心) 并且必须显式调用 Windows PowerShell -但在这里,由于您需要通过Start-Process * -Verb RunAs进行CLI调用 * 以实现提升-您可以自由选择CLI可执行文件,即您可以选择调用pwsh.exe,PowerShell(核心)CLI。
  • 如果要调用 * 当前会话 * 下的 * 同一 * PowerShell可执行文件,请使用(Get-Process -Id $PID).Path
try{
  # Call Start-Process directly.
  # If the user cancels the UAC prompt, a statement-terminating error
  # occurs, which (silently) triggers the `catch` block.
  Start-Process powershell Verb RunAs -Wait -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "path\to\file"'
}
catch{
   Write-Warning "User canceled UAC prompt."
}

字符串

相关问题