INTRODUCTION
In PowerShell, there are different ways to handle errors in a script. The try and catch methods are good examples of this. Personally, these did not work for me. With the advent of PowerShell 7, error handling has improved. It is easier to identify what goes wrong. However, when using a "loop," the display can become cluttered. You can avoid this by creating an object and writing its output to a file in CSV format. This can be opened in Excel, making it easier to filter.
PARTIAL CODE EXAMPLE
foreach ($i in $dataCSV) {
Write-Host "user: $($i.upn)"
$li = Set-MgUserLicense -UserId $i.upn -AddLicenses @() -RemoveLicenses $removeLicenses.SkuId -ErrorAction SilentlyContinue
if ($null -eq $li) {
$li
$error = Get-Error
write-verbose "$($error.ErrorDetails)"
$errorData += [PSCustomObject]@{
upn = $i.upn
error = $error.ErrorDetails
Trace = $error.ScriptStackTrace
} | Export-Csv -Path C:\temp\test.csv -Append -NoTypeInformation
} else {
$errorData += [PSCustomObject]@{
upn = $i.upn
error = "No Error"
Trace = $error.ScriptStackTrace
} | Export-Csv -Path C:\temp\test.csv -Append -NoTypeInformation
}
}
EXPLANATION OF CODE
The code is a part of a script where a license is removed from a person. The foreach loop retrieves data from a CSV file via the variable: dataCSV, as the name of the variable suggests. It deals with the User Principal Name, which is displayed on the screen.
Then a variable: li is created with a cmdlet that removes the license. The names of the persons come from the CSV file, and the type of license from the variable: removeLicenses. How exactly this is done is not traceable from this part of the code. But this does not matter for the explanation.
In the variable: li, you include parameters -ErrorAction "SilentlyContinue". This means that errors are not shown, and the script continues and does not stop.
We will now catch the error with an if statement. If the cmdlet cannot be executed, it has no output. In PowerShell, this is comparable to the variable $null. We capture the error with Get-Error and link it to the variable $error.
We create a new CustomObject $errorData and provide it with the data we want for the CSV file with the error message. This consists of the employee's name, whether there is an error or not. In the case of an error, the trace is displayed.
Top comments (1)
I use PowerShell primarily for quick fixes or troubleshooting when I need information about a particular object, such as details about Windows 11, or to gather data on a specific subject, like the number of users with an E5 license in Office. I only handle errors when absolutely necessary, and when I do, I follow this instruction. I hope it will be helpful for you as well when scripting with PowerShell.