How To Use The ErrorVariable Parameter With PowerShell

As an alternative to using the “$error” global variable, Jason will show us how to use the ErrorVariable parameter that’s available in PowerShell. In this video, Jason will take a look at using the ErrorVariable parameter and discuss how it can help with capturing errors in your code.
stamp are going to focus on using the error variable parameter with powershell. Let's get started. The error variable parameter is a common parameter available to all native PowerShell Commandlets in advanced functions is an alternative to using the dollar sign error global variable and will only contain the error from the most recent command that was executed in our example. We will use the error variable parameter on the Get Child Commandlets with a basic if statement monitoring our variable. If an error is present in our variable then the if statement will be executed and create the Readme text file. Executing the command we've seen error was generated and we also see that the Readme text file was created, meaning that our file error variable is storing our error record. You will notice that when I provided the variable name for the error variable parameter. I did not appear in the name with a dollar sign only the name of the variable. The dollar sign is not required and will not contain the error if used One note about the error. Variable parameter is that is less complex than using a try catch scriptblock and is a good fit for basic error handling for simple scripts. For more information on advanced error handling check out my snip on how to use try catch and filing script blocks. Now, if we look at the account property on our file error. Variable we can see the number of Error Records. It contains we can also review the error record in our variable. We can look at the exception type by running the gettype method on the exception property. In this case is an item not found exception type. It is possible to add additional errors or saying variable by pinning the variable name with a plus on. Here will execute our command and we will see the error below. Looking at the count property on our file error variable we can now see that it contains 2 Error Records. When using the error variable new records are added to the end of the array instead of the top of the array like the error global variable. So to see our most current error. We need to look at the last index, which can be seen by using the -1. Lastly, if use ignore error action with the error variable no errors are stored in the variable running. This command and then looking at the count property. We see it does not contain any error records that covers using the error variable in powershell. Thank you for watching.