[英]Powershell script to check services - start services - return status that it is started
我在一台机器上有一组服务,我需要验证它们在重新启动后是否正在运行。 我想运行一个 powershell 脚本来执行以下操作
这是我到目前为止的代码,我一直在测试变体,但我被卡住了,因为当我按下回车键时,它只是返回到一个新行并且不会启动任何已停止的服务。
$service = 'Service1','Service2','Service3'
get-service -name $service -WarningAction SilentlyContinue| Format-Table -Property
DisplayName,Status -AutoSize
foreach($services in $service){
if($service.status -ne "running"){
write-host attempting to start $service
get-service -name $service | start-service -force
}
else{
write-host all services are running and validated
}
}
通过将复数 ( $services
) 与单数 ( $service
) 颠倒,您将落入您为自己设置的陷阱。
此外,我会首先从变量列表中获取一系列服务,因此更容易查看是否所有服务都在运行
尝试:
$services = 'Service1','Service2','Service3' # an array of multiple services to check
# get an array of services that are not running
$notRunning = @(Get-Service -Name $services | Where-Object { $_.Status -ne 'Running' })
if ($notRunning.Count -eq 0) {
Write-Host "all services are running and validated"
}
else {
foreach ($service in $notRunning){
Write-Host "attempting to start $service"
Start-Service -Name $service
}
}
# now show the current status after trying to start some when needed
Get-Service -Name $services | Format-Table -Property DisplayName,Status -AutoSize
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.