Powershell Get-Eventlog对象输出问题

时间:2016-10-30 17:18:02

标签: string powershell object output

我在使用变量的输出作为我脚本中的输入时出现问题。

当我运行时:

$listoflogs = Get-EventLog -List | Select "Log"


$listoflogss | % { Get-EventLog -LogName $_ | Where-Object {$_.EntryType -Match "Error"} }

我收到以下错误,我明白它不会将对象作为输入处理。

Get-EventLog : The event log '@{Log=System}' on computer '.' does not exist. At line:5 char:31
+ $listoflogs | % { Get-EventLog <<<<  -LogName $_ | Where-Object {$_.EntryType -Match "Error"} }
    + CategoryInfo          : NotSpecified: (:) [Get-EventLog], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetEventLogCommand
Get-EventLog : The event log '@{Log=ThinPrint Diagnostics}' on computer '.' does not exist. At line:5 char:31
+ $listoflogs | % { Get-EventLog <<<<  -LogName $_ | Where-Object {$_.EntryType -Match "Error"} }
    + CategoryInfo          : NotSpecified: (:) [Get-EventLog], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetEventLogCommand
Get-EventLog : The event log '@{Log=Windows PowerShell}' on computer '.' does not exist. At line:5 char:31
+ $listoflogs | % { Get-EventLog <<<<  -LogName $_ | Where-Object {$_.EntryType -Match "Error"} }
    + CategoryInfo          : NotSpecified: (:) [Get-EventLog], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetEventLogCommand

然后我修改了将对象转换为字符串的脚本,但仍然无法获得我想要的输出。

$listoflogs = Get-EventLog -List | Select "Log"

$listoflogss = ($listoflogs | Out-String)

$listoflogss | % { Get-EventLog -LogName $_ | Where-Object {$_.EntryType -Match "Error"} }

Get-EventLog : Event log names must consist of printable characters and cannot contain \, *, ?, or space s At line:7 char:32
+ $listoflogss | % { Get-EventLog <<<<  -LogName $_ | Where-Object {$_.EntryType -Match "Error"} }
    + CategoryInfo          : NotSpecified: (:) [Get-EventLog], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.GetEventLogCommand

我不知道我做错了什么,是否有更好的完成这项任务。不过,我不介意理解将对象输出转换为脚本的可读字符串的概念。

2 个答案:

答案 0 :(得分:0)

经过一些测试后,我想我明白了你想要达到的目标:

Get-EventLog -List | ForEach-Object {

    $logName = $_.Log

    Get-EventLog $logName |
        Where-Object { $_.EntryType -Match "Error" } |
        Select-Object *, @{ n = "LogName"; e = { $logName } }
}

Select-Object cmdlet允许您动态创建属性以显示它(此处需要将日志名称添加到显示的结果中)。

*表示所有原始属性ne都是nameexpression的缩写,并描述了我们想要的其他属性。这称为calculated property

在原始代码中,-ExpandProperty有帮助,因为您将对象集合传递给Get-EventLog,而未指定您在Log属性之后。但Select属性也意味着您从正在收集的对象中删除所有其他属性。

你也可以像这样压制错误:

$listoflogss |
    ForEach-Object {
        Get-EventLog -LogName $_.Log |
        Where-Object { $_.EntryType -Match "Error" }
    }

答案 1 :(得分:-1)

尝试类似这样的事情

  Get-EventLog -list | where {$_.Entries.Count -gt 0} | %{ $_.Entries } | where EntryType -EQ "Error"