我需要检查是否在不同的Windows服务器上运行服务。可以运行两种服务(旧版本或新版本,或者两者都有,名称略有不同(
需要这样的输出:";新版本"旧版本";或";两个版本";
我想简单地使用Get-Process
命令进行检查,但我无法真正得出如何获得输出以及如何检查两者是否都在运行的结论。
开始时如下:如何完成我的脚本?还是我完全错了?找不到任何有帮助的东西。
if (Get-Service "NAME" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{Write-Host "New Client running"
}
if (Get-Service "NAME_old" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{Write-Host "old Client running"
}
Else {Write-Host ”No Client found”}
显然这个剧本不太好用。在服务器上测试,其中只有新客户端在运行,并且它输出:
New Client running
No Client found
将第二个if
语句更改为elseif
-这样,else
块仅在以下两个条件均不成立时运行:
if (Get-Service "NAME" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{
Write-Host "New Client running"
}
elseif (Get-Service "NAME_old" -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq "Running"})
{
Write-Host "old Client running"
}
else {
Write-Host "No Client found"
}
如果您跟踪Get-Service
结果,您可以使用三个if
语句来实现这一点:
if ($newclient = Get-Service "NAME" -ErrorAction SilentlyContinue | Where Status -eq Running) {
Write-Host 'New Client running'
}
if ($oldclient = Get-Service "NAME_old" -ErrorAction SilentlyContinue | Where Status -eq Running) {
Write-Host 'old Client running'
}
if (-not ($newclient -or $oldclient)) {
Write-Host 'No Client found'
}
略有不同的方法:
"name1", "name2" | Get-Service | foreach-object {
write-host $_.name $_.status
}
当然,这取决于之后所需的逻辑
如果您对更具可扩展性的解决方案感兴趣,我建议如下:
每次脚本找到正在运行的服务时,我都使用$appsRunning来递增,因此,如果您对正在运行的(来自$services列表的(服务的总数感兴趣,可以使用该变量。
$services = @(
[pscustomobject]@{ Name = "NAME"; Description = "New App" },
[pscustomobject]@{ Name = "NAME_old"; Description = "Old App" }
)
$appsRunning = 0
foreach ($service in $services) {
$app = Get-Service $service.Name
if ($app.status -eq "Running"){
write-host $service.Description is $app.status
$appsRunning++
}
}
if ($appsRunning -eq 0) {
Write-Host "No app Running"