簡體   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