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.