我在 PowerShell 腳本中有很多代碼,這些代碼混合了需要提升才能運行的命令和不需要提升的命令,那些需要提升的命令在 PowerShell 控制臺中顯示錯誤,例如:
"You don't have enough permissions to perform the requested operation"
和
"Requested registry access is not allowed."
有沒有辦法全域抑制由于缺乏必要的權限而導致 PowerShell 顯示的錯誤型別?
我想到了一個檢查海拔并根據結果執行操作的函式,如下所示:
https://devblogs.microsoft.com/scripting/use-function-to-determine-elevation-of-powershell-console/
Function Test-IsAdmin
{
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal $identity
$principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
和
if(-NOT (Test-IsAdmin))
{ write-host "Skipping Admin command" }
else { $code }
但我不知道如何將它全域應用于整個腳本,以便運行不需要提升的命令,以及需要提升的命令顯示自定義訊息或靜默跳過該部分。
可以幫助我的情況的另一件事是在實際運行之前確定 PowerShell 命令是否需要提升,并由于缺乏權限而導致它在控制臺中顯示錯誤。
uj5u.com熱心網友回復:
似乎由于缺乏特權而導致的錯誤通常(但不一定)涉及幕后的 .NET 例外,其名稱隨后反映為生成的 PowerShell 錯誤記錄的屬性的一部分,該System.UnauthorizedAccessException記錄的型別為.System.Security.SecurityException.FullyQualifiedErrorIdSystem.Management.Automation.ErrorRecord
假設這適用于您關心的所有錯誤,您可以使用(不再使用)trap陳述句,如下所示:
trap {
if ($_.FullyQualifiedErrorId -match 'UnauthorizedAccessException|SecurityException') {
Write-Warning "Skipping admin command ($($_.InvocationInfo.Line.Trim()))"
continue # Suppress the original error and continue.
}
# If the error was created with `throw`, emit the error and abort processing.
# SEE CAVEAT BELOW.
elseif ($_.Exception.WasThrownFromThrowStatement) { break }
# Otherwise: emit the error and continue.
}
# ... your script
警告:
如果您的腳本隱式引發腳本終止錯誤 - 通過
-ErrorAction Stop或$ErrorActionPreference = 'Stop'- 上述解決方案實際上將它們變成陳述句終止錯誤并繼續執行(只有使用陳述句創建的顯式腳本終止錯誤在throw上面的代碼中被識別為這樣,并且結果在腳本中止)。不幸的是,從 PowerShell 7.2.x 開始,通常無法發現給定錯誤是 (a)非終止、(b)陳述句終止還是 (c)腳本終止(致命)。
- 有關向 [ ] 添加屬性以允許將來進行此類發現的建議,請參見GitHub 問題 #4781 。
System.Management.Automation.ErrorRecord
- 有關向 [ ] 添加屬性以允許將來進行此類發現的建議,請參見GitHub 問題 #4781 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528274.html
上一篇:以星號顯示乘數(在C中)
下一篇:在mydict[變數]中使用函式。KeyError:<functionmyfunctionat0x7f6b65a0f7f0>
