1

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

这是代码:

$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
}

最后我需要正确的代码,就目前而言,脚本可以很好地收集/存储哈希表数组中的数据$CheckServer,但我只想选择那些需要操作的服务器。所以,如果我正在扫描 100 台服务器,其中 2 台处于 ping 失败状态,我只想要那些被选中并发送到Export-Csv.

4

2 回答 2

1

如果您只想要在输出中不响应的服务器,那么在服务器列表上使用过滤器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
于 2016-02-09T08:47:18.937 回答
0

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

$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 "...."
于 2016-02-09T06:42:11.137 回答