2

I have two services one of the service name is wrong (Spooler1). When I run the Invoke-command to stop the service using try catch block it is resulting wrong message.

Example:

[array]$Services = "spooler1","spooler"
$ComputerName = 'localhost'
For ($i=0; $i -lt $Services.Count; $i++)
{
    Try
        {
            #Stop service
            Invoke-Command -ComputerName $ComputerName -ScriptBlock {param($Service) Stop-Service $Service} -ArgumentList $Services[$i]
            Write-Host "Try Block"
        }
    Catch
        {
            Write-Host "Catch Block"

        }
}

Result:

Cannot find any service with service name 'spooler1'.
+ CategoryInfo          : ObjectNotFound: (spooler1:String) [Stop-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.StopServiceCommand
+ PSComputerName        : localhost

Try Block
Try Block

When I run above Powershell Script it is resulting message 'Try Block' for both the services.

But the result should be

Catch Block
Try Block

Do we have any workaround to fix this issue.

Ramesh Murugesan
  • 601
  • 2
  • 9
  • 16

2 Answers2

2

After adding ErrorAction stop at the end of the Invoke-command statement it is handling error correctly.

..
Invoke-Command -ComputerName $ComputerName -ScriptBlock {param($Service) Stop-Service $Service} -ArgumentList $Services[$i] -ErrorAction Stop

Result:

Catch Block
Try Block
Ramesh Murugesan
  • 601
  • 2
  • 9
  • 16
1

Invoke-Command is returning a non-terminating error when it cannot find the first service, which does not trigger the catch{} block.

As you have discovered, by explicitly specifying -ErrorAction Stop this causes the error from the cmdlet to be handled as a terminating error and therefore trigger the catch{}.

https://blogs.technet.microsoft.com/heyscriptingguy/2015/09/16/understanding-non-terminating-errors-in-powershell/

Charlie Joynt
  • 4,411
  • 1
  • 24
  • 46