For one reason or another I can't seem to get Invoke-Command to produce an error and go the Catch block of my code. I'm probably missing something obvious here, but I can't see it.
I know that the Try block is always executed until a Terminating error is found. By using the switch -ErrorAction Stop, I expect it to become a Terminating error when the server name doesn't exist and move on to the Catch block to report on this error. But it's not really doing that, it just launches the job with Invoke-Commandon the non-existing server. And when not using the switch -AsJob the error is catched. I'm a bit confused on what the best way would be for error handling here..
$Server = "Wrong"
Try {
if ($Server -eq "UNC") {
Write-Host "Running Start-Job" -ForegroundColor Cyan
Start-Job -ScriptBlock { Write-Host "Foo Start-Job" } -Name DelFiles
}
else {
Write-Host "Running Invoke-Command" -ForegroundColor Cyan
Invoke-Command -ScriptBlock { Write-Host "Foo Invoke-Command" } -ComputerName "$Server" -AsJob -JobName DelFiles -ErrorAction Stop
}
}
Catch {
Write-Host "Error detected"
}
Thank you for your help guys, I learned a lot here on StackOverflow. Once I'm getting better at PowerShell I hope to be able to help others out to.