我正在编写一个简单的脚本来解析一些事件日志,但是当没有结果的时候,或者如果instanceid无效的时候,我需要沉默一些错误:
PS C:\> get-eventlog Application -instanceid 1111
Get-EventLog : No matches found
At line:1 char:13
+ get-eventlog <<<< Application -instanceid 1111
+ CategoryInfo : ObjectNotFound: (:) [Get-EventLog], ArgumentException
+ FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand我可以做到这一点,让它安静下来,但这也会使其他错误安静下来:
PS C:\> try { get-eventlog Application -instanceid 1111 -erroraction stop } catch { }我试过了,但没有用:
PS C:\> try { get-eventlog Application -instanceid 1111 -erroraction stop } catch [ObjectNotFound] { }
Unable to find type [ObjectNotFound]: make sure that the assembly containing this type is loaded.
At line:1 char:91
+ try { get-eventlog Application -instanceid 1111 -erroraction stop } catch [ObjectNotFound] <<<< { }
+ CategoryInfo : InvalidOperation: (ObjectNotFound:String) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound发布于 2014-10-18 00:32:59
您可以使用-ErrorAction SilentlyContinue并在其之后检查$error变量,
$error[0] 它将始终包含最后一个错误对象。
发布于 2014-10-18 00:02:22
这绝不是唯一的选择,但您可以尝试这样的方法:
$result = get-eventlog Application -instanceid 1111 -erroraction silentlycontinue
if($result){
Write-Host "Found some."
} else{
Write-Host "wah wah wah waaaah... you know like the trombone sound"
}再一次,我没有完全阅读一篇文章。为了使我的回答更好,我提供了这个,这可能会帮助你的try块的麻烦。
try {
get-eventlog Application -instanceid 1111 -ErrorAction Stop
} Catch [Exception]{
$theError = $_
Switch($theError .Exception.GetType().FullName){
System.InvalidOperationException{Write-Host "This happened: $($theError.Exception.Message)"}
System.ArgumentException {Write-Host "This happened: $($theError.Exception.Message)"}
default{"Something else happened: $($theError.Exception.GetType().FullName)"}
}
}使用-Stop创建终止错误。捕获任何异常并将error对象放入变量中,以便以后可以在其他作用域中使用。获取异常名称,并在其上使用开关语句来确定适当的操作。在“没有找到匹配”的情况下,会抛出一个[System.ArgumentException],通过查看$_.Exception.GetType().FullName的值就可以看出这一点。捕获开关语句中的特定错误,如果您还没有捕捉到一个特定的异常,则可以在default中查看详细信息。
当我在cmdlet调用"Fizgig“中替换"Application”时,[System.InvalidOperationException]发生了什么?
发布于 2015-06-17 13:54:04
您应该尝试使用以下语法来获得错误,同时不停止脚本的执行:
try
{
# check for eventLog
Get-EventLog -LogName "Application" -InstanceId 1111 -ErrorAction Stop
}
catch
{
# send error as ID
Write-Warning "Error -Message $($_.Exception.Message) -Line $($_.InvocationInfo.ScriptLineNumber) -Time $(Get-Date -Format 'HH.mm.ss.fff')"
}https://stackoverflow.com/questions/26434831
复制相似问题