I'm trying to catch the error from service restart using function. The issue Im having that catch is not doing anything through the script.
Function Service_Restart ($Servers, $Service){
try {
Write-Host "$CurrentDateTime - Restarting Service $Service on Servers $Servers"
ForEach($Serv in $Servers){
Get-Service -ComputerName $Serv -Name $Service | Restart-Service
}
} catch [System.ServiceProcess.ServiceController] {
$error[0].Exception
}
Service_Restart Server1 ServiceName
I'm expecting to see an one line error not the full stack, however I see the entire error.
What I like to see as an example
Restart-Service : Service 'Adobe Acrobat Update Service (AdobeARMservice)' cannot be stopped due to the following error: Cannot open AdobeARMservice service on computer 'Localhost'.
However I'm seeing
Restart-Service : Service 'Adobe Acrobat Update Service (AdobeARMservice)' cannot be stopped due to the following error: Cannot open AdobeARMservice service on computer 'Localhost'.
At C:\user\UTILS_Version3.ps1:48 char:62
+ ... Get-Service -ComputerName $Serv -Name $Service | Restart-Service
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (System.ServiceProcess.ServiceController:ServiceController) [Restart-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStopService,Microsoft.PowerShell.Commands.RestartServiceCommand
If I run $error[0].Exception manually I get the result I'm looking for but not through the function.
PS C:\Users\> $error[0].Exception
Service 'Adobe Acrobat Update Service (AdobeARMservice)' cannot be stopped due to the following error: Cannot open AdobeARMservice service on computer '127.0.0.1'.
PS C:\Users\>