[英]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.