What is use of $error variable in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

Error variable in PowerShell is to view the errors generated in the current PowerShell session. We can say that the $Error variable is the container that stores all the errors and the latest error will be displayed first. For the example below, we will set the $Errorview to Category view to minimizing the error display content. By default $ErrorView is a Normal view.

$ErrorView = "Categoryview"

Now we will see the $error variable example,

PS C:\WINDOWS\system32> asdds
ObjectNotFound: (asdds:String) [], CommandNotFoundException
PS C:\WINDOWS\system32> Get-process asddsd
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException

Here, there is one wrong command and one wrong input we have written so let see what $error variable contains.

PS C:\WINDOWS\system32> $error
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException

In the above output, the last error will be displayed first, and so on. $Errorvariable has become an array now. You can get the individual output as an array typical method.

PS C:\WINDOWS\system32> $error[0]
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
PS C:\WINDOWS\system32> $error[1] ObjectNotFound: (asdds:String) [], CommandNotFoundException

To get the count of errors generated,

PS C:\WINDOWS\system32> $error.Count
2

To check the error capacity, you can run the below command.

PS C:\WINDOWS\system32> $error.Capacity
4

When the capacity of storing error reaches 4, again this variable automatically increases its capacity by 4, so the total capacity becomes 8. So every time the error variable reaches its capacity, it increases the capacity by 4.

For example,

We already created 4 errors here,

PS C:\WINDOWS\system32> $error
ObjectNotFound: (221dsd:String) [], CommandNotFoundException
ObjectNotFound: (7sdse:String) [], CommandNotFoundException
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException

When you add one more error count,

PS C:\WINDOWS\system32> 5look
ObjectNotFound: (5look:String) [], CommandNotFoundException

Now check the capacity,

PS C:\WINDOWS\system32> $error.Capacity
8

And the output,

PS C:\WINDOWS\system32> $error
ObjectNotFound: (5look:String) [], CommandNotFoundException
ObjectNotFound: (221dsd:String) [], CommandNotFoundException
ObjectNotFound: (7sdse:String) [], CommandNotFoundException
ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException
ObjectNotFound: (asdds:String) [], CommandNotFoundException

So question is, what is the threshold for this error variable capacity? To check it, you need to use the command $MaximumErrorCount.

PS C:\WINDOWS\system32> $MaximumErrorCount
256

Here, the limit of the maximum error count is 256.

raja
Published on 27-May-2020 12:53:40
Advertisements