我目前有一个脚本,它会ping服务器列表并检查每台服务器上运行的服务的状态。我想写入log.csv。
我想显示哪些计算机处于脱机状态,并显示哪些服务处于已停止状态。
如何使用PSCustumObject获取计算机或计算机名称? CSV输出只有一行表示离线,但它没有列出前面的计算机名称。
$serviceList = Get-Content C:\services.txt
$results = Get-Content C:\servers.txt | ForEach-Object {
if (Test-Connection -ComputerName $_ -BufferSize 16 -Count 1 -EA 0 -Quiet) {
foreach ($service in $serviceList) {
if ($s=get-service -computer $_ -name $service -ErrorAction SilentlyContinue)
{
$s | select MachineName, ServiceName, Status, StartType
} else {
# "$_ - Service '$service' does not exist."
}
}
} else {
$status = Write-Output "Offline"
}
[pscustomobject][ordered]@{
Machine = $_
Status = $status
}
}
$results | Export-CSV C:\log.csv -notypeinformation -Append
答案 0 :(得分:2)
当您从Get-Service
输出结果时,您需要选择MachineName
:
$s | select MachineName, ServiceName, Status, StartType
然后,对于离线计算机,您使用Machine
构建对象:
[pscustomobject][ordered]@{
Machine = $_
Status = $status
}
您需要将自定义对象更新为MachineName
,以便它与您在上面选择的属性相匹配。
它还需要移至else{}
(替换$status = Write-Output "Offline"
),以便仅在计算机离线时调用它。
然后,您将获得您期望的输出:
MachineName ServiceName Status StartType ----------- ----------- ------ --------- localhost spooler Running Automatic localhost DusmSvc Running Automatic localhost DeviceInstall Stopped Manual noname Offline
更新了代码,并对不存在的服务进行了奖励更新:
$serviceList = Get-Content C:\services.txt
$results = Get-Content C:\servers.txt| ForEach-Object {
if (Test-Connection -ComputerName $_ -BufferSize 16 -Count 1 -EA 0 -Quiet) {
foreach ($service in $serviceList) {
if ($s = get-service -computer $_ -name $service -ErrorAction SilentlyContinue) {
$s | select MachineName, ServiceName, Status, StartType
}
else {
[pscustomobject][ordered]@{
MachineName = $_
ServiceName = $service
Status = "NotFound"
}
}
}
}
else {
[pscustomobject][ordered]@{
MachineName = $_
Status = "Offline"
}
}
}
$results | Export-CSV C:\log.csv -notypeinformation -Append