简体   繁体   English

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

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

I have a set of services on a machine that I need to validate are running after reboots.我在一台机器上有一组服务,我需要验证它们在重新启动后是否正在运行。 I would like to run a powershell script that will do the following我想运行一个 powershell 脚本来执行以下操作

  1. Show current status of services显示服务的当前状态
  2. Show which services are not running显示哪些服务没有运行
  3. actually Start the services实际启动服务
  4. lastly check and return confirmation that all services are running最后检查并返回确认所有服务都在运行

This is the code I have so far and I've been testing variations but I'm stuck as when I hit enter, it just returns to a new line and does not start any of the stopped services.这是我到目前为止的代码,我一直在测试变体,但我被卡住了,因为当我按下回车键时,它只是返回到一个新行并且不会启动任何已停止的服务。

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

You are falling into the trap you set for yourself by reversing the multiple ( $services ) with the singular ( $service ).通过将复数 ( $services ) 与单数 ( $service ) 颠倒,您将落入您为自己设置的陷阱。

Also, I would first get an array of services from your list in a variable, so it is easier to see if all are running or not此外,我会首先从变量列表中获取一系列服务,因此更容易查看是否所有服务都在运行

Try:尝试:

$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