以下代码旨在检查两个硬编码的服务名称(这些名称永远不会更改),如果找不到它们,则说明服务不存在。它这样做但它输出两行,因为有两个服务要检查。
有没有办法改变这一点,以便在检查两个服务后只给出一个输出?
$servicenames = ("Service 1", "Service 2")
Write-Host 'Checking for Services'
function servicevalidation {
foreach ($sn in $servicenames) {
if ((Get-Service "$servicenames*" -Include $servicenames) -eq $null) {
Write-Host 'Young jedi you are mistaken, this server is not a collector!'
} else {
Write-Host "$servicenames present"
}
}
}
答案 0 :(得分:0)
Get-Service
接受服务列表,因此您可以在没有循环的情况下执行以下操作。不过,如果你将检查封装在一个函数中,我建议将服务作为参数传递。
function servicevalidation($svc) {
if (Get-Service $svc -ErrorAction SilentlyContinue) {
Write-Host 'Young jedi you are mistaken, this server is not a collector!'
} else {
Write-Host "$svc present."
}
}
servicevalidation $servicenames
如果服务不存在,-ErrorAction SilentlyContinue
会抑制错误输出。
如果您想知道哪些服务确实缺失,您可以使用Where-Object
过滤器执行此操作:
function servicevalidation($svc) {
$missing = $svc | Where-Object {
-not (Get-Service $_ -ErrorAction SilentlyContinue)
}
if ($missing) {
Write-Host "missing service: $missing"
} else {
Write-Host "$svc present."
}
}