ICT

[PowerShell]8. Exception(error) Handling

NeoSailer 2023. 5. 2. 15:57

Scripts do not always go as intented. Errors in the middle of task can harm data reliability. For example, Active Directory user account inactivation script stops in the middle the task and it only partly removed AD groups which is related to Office 365 licenses. This can mislead that the user account has been deactived as status but actually the business ends up paying license fees until someone notices it. To prevent this mishap, exception(error) handling should be applied when especially running CRUD(Create, Read, Update, Delete) related commands.

 

PowerShell provides "try", "catch" and "finally" exception handling commands as below.

try {
    # Code that might generate an exception
    $result = Get-ChildItem -Path "C:\NonExistentFolder"
}
catch {
    # Code that handles the exception
    Write-Error "An error occurred: $($_.Exception.Message)"
}
finally {
    # Code that is always executed, whether or not an exception occurred
    Write-Host "Script execution completed."
}

 

In addition to that, error message can be handled manually by "throw" statement.

function Divide-Numbers ($numerator, $denominator) {
    if ($denominator -eq 0) {
        throw "Cannot divide by zero."
    }
    return $numerator / $denominator
}

try {
    $result = Divide-Numbers 10 0
}
catch {
    Write-Error "An error occurred: $($_.Exception.Message)"
}

In the commands, "throw" catches the error when nominator is divided by zero.

 

Practically, script writer should consider the number of cases what could possible go wrong. The more you care about script error with exception handling, the less errand to remediate the affect from bad script in the future.

반응형