A try/catch statement attempts an operation in a Try block and responds when an exception occurs in the Catch block. Once an exception occurs, later statements in Try are skipped. In PowerShell, use -ErrorAction Stop when necessary so an error reaches Catch instead of being suppressed or continuing unnoticed. section 24.4
A practical error-handling pattern can include:
- Try the operation, such as creating a remote session or finding a computer in Active Directory. section 22.1.2 section 24.4
- Catch the failure and provide a warning, log the error, or create an alternate result. section 22.1.2 section 24.4
- Use typed Catch blocks for known exception types, followed by an untyped Catch for anything else. section 24.6
- Use an optional Finally block for work that must run after either Try or Catch. section 24.6
Classifying computer results
A loop can try Get-ADComputer for each computer. On success, it records the computer as enabled and present in Active Directory; on failure, Catch records that it is not in Active Directory. The resulting properties can then become output objects. section 22.1.2
Try {
# something here generates an exception
} Catch [Exception.Type.One] {
# deal with that exception here
} Catch [Exception.Type.Two] {
# deal with the other exception here
} Catch {
# deal with anything else here
} Finally {
# run something else
}
This pattern shows typed exception handling, a general fallback, and a Finally block in one compact structure. section 24.6
Try/Catch is the structured approach recommended for new PowerShell code; Trap remains only for backward compatibility and is deprecated. ErrorVariable and $Error can preserve error information, but Try/Catch works reliably here with terminating errors. section 24.6 section 24.7









