我的脚本中出现错误

时间:2018-08-10 20:13:05

标签: powershell scripting powershell-remoting

我不断收到一条错误消息,指出

"Exception calling "Start" with "0" argument(s): "Cannot start service RTCRGS on computer 'CORPxxxxxxx.xxxx.net'."
At line:25 char:18
+          $_.Start <<<< () 
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException"

关于这种情况为什么发生以及如何解决的任何建议?

$services = "RTCRGS"
$SvrName = 'CORPxxxx.xxxx.xxxx'
Get-Service -ComputerName $SvrName -Name $services | % {
    Write-host "$($_.Name) on $SvrName is $($_.Status)"
    if ($_.Status -eq 'stopped') {
        Write-Host "Starting $($_.Name) in 5 sec..."
        Start-Sleep 5
        Write-Host "$($_.Name) is Starting, please wait..."
        $_.Start()
        Write-Host "Checking status of service, please wait for 25 sec..."
        Start-Sleep 20
        Write-Host "$($_.Name) on $SvrName is $($_.Status)"
    } elseif ($_.Status -eq 'running') {
        Write-Host "Restaring $($_.Name) in 5 sec..."
        Start-Sleep 5
        $_.Stop()
        Start-Sleep 5
        Write-Host "$($_.Name) is Starting, please wait..."
        $_.Start()
        Write-Host "Checking status of service, please wait for 25 sec..."
        Start-Sleep 25
        Write-Host "$($_.Name) on $SvrName is $($_.Status)"
    }
}

1 个答案:

答案 0 :(得分:0)

如果未禁用该服务(并且已检查您可以手动重新启动该服务),那么使用类似这样的方法可能会更好

$services = "RTCRGS"
$SvrName = 'CORPxxxx.xxxx.xxxx'
Get-Service -ComputerName $SvrName -Name $services | ForEach-Object {
    Write-host "$($_.Name) on $SvrName is $($_.Status)"

    if (@("Stopped","StopPending","Paused","PausePending") -contains $_.Status) {
        Write-Host "Starting service $($_.Name), please wait..."
        $_.Start()
    } 
    else {
        Write-Host "Stopping service $($_.Name)..."
        $_.Stop()
        # as HAL9256 suggested, perform a loop to see if service has really stopped
        do {
            # recheck the ACTUAL status, not the status you captured before
            $newStatus = (Get-Service -ComputerName $SvrName -Name $_.Name).Status
        } while ($newStatus -ne "Stopped")
        Write-Host "$($_.Name) is Restarting, please wait..."
        $_.Start()
    }

    Write-Host "Checking status of service, please wait for 25 sec..."
    Start-Sleep 25

    # here again you should recheck the ACTUAL status, not the status you captured before
    $newStatus = (Get-Service -ComputerName $SvrName -Name $_.Name).Status
    Write-Host "$($_.Name) on $SvrName is $newStatus"
}

您可以读取“状态” here

的可能值