繁体   English   中英

Powershell 检查服务的脚本 - 启动服务 - 返回它已启动的状态

[英]Powershell script to check services - start services - return status that it is started

我在一台机器上有一组服务,我需要验证它们在重新启动后是否正在运行。 我想运行一个 powershell 脚本来执行以下操作

  1. 显示服务的当前状态
  2. 显示哪些服务没有运行
  3. 实际启动服务
  4. 最后检查并返回确认所有服务都在运行

这是我到目前为止的代码,我一直在测试变体,但我被卡住了,因为当我按下回车键时,它只是返回到一个新行并且不会启动任何已停止的服务。

$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM