哈希表过滤器 / select

hashtable filter / select

我今晚正在重新编写现有的服务器运行状况检查脚本以将其值存储在哈希表中,并且该部分工作正常。但是,我希望将结果转到 CSV 文件,并且该文件只填充我已将它们标记为需要操作的服务器。当前,这些正在生成事件 ID 7011,或者通过 Test-Connection 未能通过 ping 测试。

代码如下:

$CheckServer = @{}
$Servers = (Get-Content $Dir\Test.txt)
foreach ($Server in $Servers) {
    $CheckServer.EventID7011 = Get-Eventlog -LogName System -ComputerName $Server -Newest 1 |
        Where-Object {$_.EventId -eq 7011} | select Message
    if ($CheckServer.EventID -ne $Null) {
        $CheckServer.Server = "$Server"
        $CheckServer.ActionReq = "Yes"
    }

    $CheckServer.Ping = Test-Connection -ComputerName $Server -Count 1 -Quiet
    if (! $CheckServer.Ping) {
        $CheckServer.Server = "$Server"
        $CheckServer.ActionReq ="Yes"
        $CheckServer.Ping = "Offline"
    } else {
        $CheckServer.Server = "$Server"
        $CheckServer.ActionReq = "No"
        $CheckServer.Ping = "Online"
    }

    New-Object -TypeName PSObject -Property $CheckServer |
        Export-Csv "ScanResults.csv" -NoTypeInformation -Append
}

我最后需要正确的代码,就目前而言,该脚本适用于 collecting/storing 哈希表数组 $CheckServer 中的数据,但我只想 [=24] =] 那些需要操作的服务器。所以,如果我正在扫描 100 台服务器,其中 2 台处于 ping 失败状态,我只想要那些 selected 并发送到 Export-Csv.

您需要先将对象存储到列表中,然后才能过滤和导出它们。查看代码中带有注释的行:

$CheckServer = @{}
$serverObjects = @() # create a list of server objects
$Servers = (get-content $Dir\Test.txt)
ForEach ($Server in $Servers) {

$CheckServer.EventID7011 = get-eventlog -LogName System -ComputerName
$Server -newest 1 | where-object {$_.eventID -eq 7011} |select message
If ($CheckServer.EventID -ne $Null) {
$CheckServer.Server="$Server"
$CheckServer.ActionReq = "Yes"}

$CheckServer.Ping = Test-Connection -ComputerName $Server -count 1 -quiet
if (! $CheckServer.Ping) {
    $CheckServer.Server="$Server"
    $CheckServer.ActionReq ="Yes"
    $CheckServer.Ping= "Offline"}

Else {
    $CheckServer.Server="$Server"
    $CheckServer.ActionReq ="No"
    $CheckServer.Ping= "Online"}

    # Add the server object to the list
        $serverObjects += New-Object -TypeName PSObject -Property $CheckServer 
    }
}
# now filter it:
$serverObjects | where ActionReq -eq "Yes" | Export-Csv -Path "...."

如果您只想在输出中不响应 Test-Connection 的服务器,那么在服务器列表上使用 Where-Object 过滤器会简单得多:

Get-Content "$Dir\Test.txt" |
    Where-Object { -not (Test-Connection -Computer $_ -Count 1 -Quiet) } |
    Select-Object @{n='Server';e={$_}}, @{n='ActionReq';e={'Yes'}},
                  @{n='Ping';e={'Offline'}} |
    Export-Csv 'ScanResults.csv' -NoType -Append