我想检查 (.txt) 服务器列表以查看 (a) 服务器是否在线,如果在线,则检查 (b) 特定服务是否存在
它应该执行以下操作(高级概述):
我当前的代码 当前代码只是跳过通过测试连接测试但没有服务的服务器
$serverlist = Get-Content "C:\BTPM-PS-Scripts\servers.txt"
foreach ($server in $serverlist){
if(Test-Connection -ComputerName $server -Count 1 -Quiet)
{
Invoke-Command -computername $server -ScriptBlock {
Get-Service -name WHATEVERSERVICE }
}
else
{
Write-Host "Server $server not found" -ForegroundColor Yellow
}
}
我根本不知道从这里该去哪里。我首先想到使用 IF 和 ELSEIF,但我认为这不能完全满足我的需要,或者也许?
我知道这根本没有意义(菜鸟)。但这是我尝试过的,当然没有用。
foreach ($server in $serverlist){
if(Test-Connection -ComputerName $server -Count 1 -Quiet)
{
**NOT ACTUAL CODE BUT SHOULD CONTINUE IF "TEST-CONNECTION" CONDITION IS TRUE**
}
if(Invoke-Command -computername $server -ScriptBlock {Get-Service -name stor*})
{
write-host "service exists"
}
elseif(Write-Host "stupid service doesn't exist")
{
continue
}
{
Invoke-Command -computername $server -ScriptBlock {
Get-Service -name avecto* }
}
else
{
Write-Host "Server $server not found" -ForegroundColor Yellow
}
}
Invoke-Command
的能力,通过 -ComputerName
定位多台计算机。
收集任何错误 - 无论是由于无法开始连接还是由于
Get-Service
在成功连接后未在目标计算机上找到服务 - 使用 通用 -ErrorVariable
参数。
在事后打印任何错误,例如,使用通过 [System.Management.Automation.ErrorRecord]
收集的
-ErrorVariable
实例的属性,结合 Format-Table
和 计算属性。
# Target all computers in parallel and output success output.
# Silence errors, but collect them in self-chosen variable $errs
# for later processing.
Invoke-Command -ErrorAction SilentlyContinue -ErrorVariable errs -ComputerName (Get-Content C:\BTPM-PS-Scripts\servers.txt) {
Get-Service -Name WHATEVERSERVICE
}
# Print errors, if any, grouped by category
$errs |
Format-Table -Force -GroupBy CategoryInfo -Property `
@{ Name='ComputerName'; Expression={ if ($_.OriginInfo) { $_.OriginInfo } else { $_.TargetObject } } }
@{ Name='ErrorMessage'; Expression={ $_.ToString() } }