首页 > 解决方案 > 在 PowerShell v2.0 中导入和测试正在运行的服务列表

问题描述

我一直在编写一个脚本来从服务器复制正在运行的服务,然后导出该列表。重新启动服务器后,我们将列表与重新启动的服务器上运行的服务进行比较,并重新启动任何未启动的服务。问题是服务器是 2.0 版,我没有更新服务器的选项。我的代码如下所示:

# To create the list of services in text file
(Get-Service | Where-Object {$_.Status -eq "Running"}).Name |
    Out-File "C:\ListOfServices.txt"
# For testing add BlackJack as a service that doesn't exist 

#Restart-Computer -Force
Write-Host "Starting required services " -ForegroundColor Cyan
$date = Get-Date -Format G 
Write-Host $date -ForegroundColor Cyan
# Services array needed to be started when the Server comes back up 
$ServiceNameArray = Get-Content -Path "C:\ListOfServices.txt"

foreach ($serviceName in $ServiceNameArray) {
    if (Get-Service $serviceName -ErrorAction SilentlyContinue) {
        if ((Get-Service $serviceName).Status -eq 'Running') {
            Write-Host "$serviceName found, and is running" -ForegroundColor Green
        } else {
            Write-Host "$serviceName found, but it is not running." -ForegroundColor Yellow

            Stop-Service -InputObject $serviceName
            Get-Service -InputObject $serviceName

            Start-Sleep 3

            Start-Service -InputObject $serviceName -ErrorAction SilentlyContinue 
            $services = $serviceName
            $maxRepeat = 20
            $status = "Stopped" # change to Stopped if you want to wait for services to start

            do {
                $count = (Get-Service $services | ? {$_.status -eq $status}).Count
                $maxRepeat--
                sleep -Milliseconds 1000
            } until ($count -eq 0 -or $maxRepeat -eq 0)

            Get-Service -InputObject $serviceName 
        }
    } else {
        Write-Host "$serviceName not found" -ForegroundColor Red
    }
}
Write-Host "Starting required services has ended" -ForegroundColor Cyan
$date = Get-Date -Format G 
Write-Host $date -ForegroundColor Cyan 
Remove-Item "C:\ListOfServices.txt"
Write-Host "Removed Services text file" -ForegroundColor Green

标签: powershell-2.0

解决方案


推荐阅读