Reputation: 5
$MDservices = ""
$tempservices = ""
try{
$alerter = Get-Service Alerter
if($alerter.Status -eq 'Running'){
$alerter = Out-String -InputObject $alerter.DisplayName
$MDservices = $tempservices + $alerter
} else {
continue
}
}
catch {
write "somethings wrong"
}
This is my powershell try catch codes. I expect this output is write "somethings wrong" becaues my pc dosen't have 'Alerter' service but it's output is printing error
What am i do guys? Help me:(
Upvotes: 0
Views: 72
Reputation: 538
Most likely due your default $ErrorActionPreference value.
Try following :
try
{ $alerter = Get-Service Alerter -ErrorAction Stop
if($alerter.Status -eq 'Running') {
$alerter = Out-String -InputObject $alerter.DisplayName
$MDservices = $tempservices + $alerter
}
else {
continue
}
}
catch
{ Write-Host "somethings wrong"
}
finally
{
Write-Host "cleaning up ..."
}
Upvotes: 0
Reputation: 24562
If the try
block does not generate a terminating error, it will not move into the Catch
block. This is controlled by -ErrorAction
parameter. By default it uses Continue
. So just change
# This will generate terminating error and move to Catch Block.
$alerter = Get-Service Alerter -ErrorAction Stop
Ref: Try/Catch/Finally…doesn’t work
Upvotes: 2