我在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命令之前,找出它是否需要提升,并使它在控制台中显示由于缺乏特权而导致的错误。
似乎错误源于缺乏特权通常 -但不一定-涉及System.UnauthorizedAccessException
或System.Security.SecurityException
. net异常的幕后,其名称然后反映为.FullyQualifiedErrorId
属性的一部分,由此产生的PowerShell错误记录,这是System.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) 脚本-终止(fatal)。
- 请参阅GitHub issue #4781,以获取向[
System.Management.Automation.ErrorRecord
]添加属性以允许将来发现此类属性的建议。
- 请参阅GitHub issue #4781,以获取向[