Logging Like a Pro in PowerShell: Harnessing the Magic of $?
- Rattandeep singh
- Sep 11, 2023
- 2 min read

PowerShell is a versatile scripting language that allows you to automate various tasks and system administration processes. One of the key aspects of writing robust and reliable PowerShell scripts is error handling and logging.
The most common way to do that will be using Try-Catch blocks.
Try Block: Inside the "Try" block, you place the code that you expect might generate an error or exception.
Catch Block: Inside the "Catch" block, you specify the actions to take if an error or exception occurs in the corresponding "Try" block. You can capture error details, log them, display custom error messages, or perform other actions to handle the error gracefully.
Here's an example of how Try-Catch blocks are used in PowerShell:
The output of the above code is..
An error occurred Cannot find path 'C:\NonExistentFile.txt' because it does not exist.
I know you are feeling that I lost track of the topic. Now let's get back to $?.
What is "$?" ?
In PowerShell, the $? variable is a special automatic variable that holds information about the success or failure of the last command or operation. It's a Boolean variable, where $true indicates success, and $false indicates an error or failure.
Why and when to you use it "$?" ?
Simplicity: $? provides a straightforward way to check if the last command succeeded or failed without the need for more complex error-handling constructs.
Quick Checks: It's useful for quick conditional statements. For example, you might use $? to determine whether to proceed with the next step in a script based on the success of the previous step.
Informal Scripting: In some cases, when writing simple, one-off scripts or interactive commands, $? can be a convenient way to make decisions based on command success or failure without writing extensive error-handling logic.
I am going to use the same example that used with Try-Catch block earlier.
Unlike try-catch block the default error is displayed on the console screen.
The script block $($_.Exception.Message) did not bring any output
To get the detailed error message, I used the global error variable and extracted the data from the index 0. $($error[0].Exception.Message)
Get-Item : Cannot find path 'C:\NonExistentFile.txt' because it does not exist.
At line:2 char:1
+ Get-Item C:\NonExistentFile.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\NonExistentFile.txt:String) [Get-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
An error occurred: !!!
An error occurred: Cannot find path 'C:\NonExistentFile.txt' because it does not exist.
As we have learned the error handling, what is the next step?
Error handling is only part of the equation. Logging is equally important, as it allows you to keep a record of script execution and any encountered errors. Here's how you can implement logging using the $? variable:
The below code will generate a log file with the time stamp, success message, and an error message.
Mastering error handling and logging is essential for writing reliable and maintainable PowerShell scripts. The $? variable provides a powerful tool for checking the success or failure of commands, allowing you to take appropriate actions based on the outcome. Combined with logging, it enables you to track script execution and diagnose issues effectively.
By incorporating error handling and logging techniques into your PowerShell scripts, you can build automation solutions that are more robust, resilient, and easier to maintain.
Comments