我想避免由null dsquery引发的错误。我试过这个:
try {
dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >> output.txt
}
catch [Exception] {
return $_.Exception.Message
}
但我还是得到了:
dsget : dsget failed:'Target object for this command' is missing.
At ExpiringCertificates.ps1:35 char:49
+ dsquery user forestroot -samid $a[$i] | dsget user -email | Select-Strin ...
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (dsget failed:'T...nd' is missing.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
type dsget /? for help.
我该如何处理?
答案 0 :(得分:1)
试试这个:
try
{
dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >> output.txt
}
catch
{
Write-Error -ErrorRecord $_
}
如果$ ErrorActionPreference设置为' Stop',Write-Error将抛出异常并停止执行。否则,它将打印到错误流并继续执行。这允许调用者决定是否继续出错并使您不必在脚本中设置全局变量。
如果需要打印并返回错误消息,请使用-ErrorVariable参数:
catch
{
$errorVar = $null
Write-Error -ErrorRecord $_ -ErrorVariable errorVar
return $errorVar
}
或者,如果您需要在不打印的情况下返回错误消息,请添加" 2>"重定向:
catch
{
$errorVar = $null
Write-Error -ErrorRecord $_ -ErrorVariable errorVar 2> $null
return $errorVar
}
答案 1 :(得分:1)
dsquery 和 dsget 不是PowerShell命令,因此PowerShell查看标准错误并对其进行处理,将其转换为带有" NativeCommandError&#的ErrorRecord 34;附加的异常,然后将该记录的文本表示发送到标准输出。
但是,如果您自己处理标准错误,则可以更灵活:
dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line 2>&1
If ($_ -is [Management.Automation.ErrorRecord]) {
$message = $_.Exception.Message
# Do what you want with $message.
} Else {
$_ >> output.txt
}
答案 2 :(得分:0)
这可能对您有用:
try {
$erroractionpreference = 'stop'
dsquery user forestroot -samid $a[$i] | dsget user -email | Select-String '@' | select -Expand Line >output
}
catch [Exception] {
return $_.Exception.Message
}