I understand try-catch-finally in Powershell, but is there something similar to Python's 'else' clause, in which code runs only if there is not an error?
I'm writing a script that uses invoke-webRequest on a site that goes down frequently. I use try-catch to catch HTTP errors. I also want a block of code to run only if the invoke-webRequest command completes successfully.
try{
invoke-WebRequest -URI 'http://flakywebsite.com/site1' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site2' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site3' -Method GET
}
catch{
"This line will execute only if there is an error in the try block"
}
else{
"This line will execute only if there is NOT an error in the try block"
}
finally{
"This code will run regardless of whether there is or is not an error in the try block."
}
I have this workaround. It uses the catch block to append a notice to the $Error variable:
try{
invoke-WebRequest -URI 'http://flakywebsite.com/site1' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site2' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site3' -Method GET
}
catch{
$Error.add("An error occurred in the try loop."}
}
if($Error[-1] -ne "An error occurred in the try loop."){
"This code will run only if there is NOT an error in the try block.
}
This works, but it's awfully ugly. Is there a better way to do this in Powershell?
if(!$Error){ "An error didn't occur" }
. – xyzInvoke-WebRequest
should (depending on your$ErrorActionPreference
ofc) trigger the switch tocatch
block, so why don't you just put the code fromelse
block belowInvoke-WebRequest
? – Robert Dyjas