You can use try, catch and finally in PowerShell for error handling.
Here is what each of these do:
A try statement “tries” to perform some operation.
Suppose that we would like to attempt to divide 1 by 0.
Suppose we type this operation in PowerShell without using a try statement:

We receive a message that says we attempted to divide by zero along with additional details.
Suppose that we would like to perform this exact same operation but display our own custom output if an error occurs.

- There was an error.
- The task is complete.
Suppose instead that we try to multiply 1 by 0:

Since it’s possible to multiply 1 by 0, the try statement produces the result of this multiplication, which is 0.
- The task is complete.
PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension
Assuming this is a simple comparison running at script level, then you should use the return keyword as your flow control. For example:
if ($true) { try { 1 / 0 return } catch { Write-Error 'fail 1' } try { 2 / 0 return } catch { Write-Error 'fail 2' } try { 'this works!' return } catch { Write-Error 'nothing here' } try { 'this doesnt run!' } catch { Write-Error 'nothing here' }
}Which would output:
Write-Error: fail 1
Write-Error: fail 2
this works!As you can see, the script exits early as soon as one of the try statements didn’t fail. Using break shouldn’t be an option in this case as it might bring unexpected results. See Do not use break outside of a loop, switch, or trap.
A simple example of why break shouldn’t be used outside of those mentioned above, given our script.ps1:
param([Parameter(ValueFromPipeline)] $inputobject)
process { if ($inputobject -eq 5) { '{0}: {1}' -f $inputobject, $true break } '{0}: {1}' -f $inputobject, $false
}If we were to try a simple pipeline input:
PS ..pwsh\> 0..10 | .\script.ps1
0: False
1: False
2: False
3: False
4: False
5: TrueWe would see that the whole pipeline terminates unexpectedly. If instead we change that break to a return we can see that the script exits early but it doesn’t terminate the whole pipeline:
PS ..pwsh\> 0..10 | .\script.ps1
0: False
1: False
2: False
3: False
4: False
5: True
6: False
7: False
8: False
9: False
10: False




