我今晚正在努力重新编写现有的服务器运行状况检查脚本,以将其值存储在哈希表中,并且该部分工作正常。但是,我希望结果转到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
}
我最后需要正确的代码,因为脚本可以正常收集/存储哈希表数组$CheckServer
中的数据,但是我只想选择那些需要的服务器行动。因此,如果我正在扫描100台服务器,其中2台处于ping失败状态,我只想选择那些并发送到Export-Csv
。
答案 0 :(得分: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
答案 1 :(得分: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 "...."