Search code examples
powershellscriptingpowershell-remoting

Getting error in my script


I keep getting an error message stating

"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"

Any suggestion on why this happens and how to fix it?

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

Solution

  • If the service is NOT disabled (and you have checked you can restart it manually) you might be better of with something like this

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

    You can read the possible values for 'Status' here