17.2. $Error
$Error is a Windows PowerShell system variable that contains an array of information about recent errors. Individual errors are accessed by using array notation, for example, the command
$Error[0]
returns element 0 of the Error array, which represents the error message for the most recent error.
When the Windows PowerShell shell is first opened the command Error[0] returns nothing to the console, since there have been no errors in the PowerShell session (assuming successful startup) and the Windows PowerShell prompt simply moves on to the next line. However, if you have run a statement that produces an error, for example
15/0
an error message is displayed, as shown in Figure 17-2, typing the following command returns the error message of the most recent error:
$Error[0]
Figure 17.2. Figure 17-2
If you run another command that is known to produce an error, for example, attempting to find a file
get-childitem Fred.txt
in a folder that doesn't have such a file, the divide by zero error is now stored in $Error[1] and the new error message about the file not being found is now returned by $Error[0]. You can demonstrate this by typing the following commands:
$Error[0] get-childitem Fred.txt $Error[1] $Error[0]
The results of running the preceding commands are shown in Figure 17-3.
Figure 17.3. Figure 17-3
If you then run another command that generates a further error, ...
Get Professional Windows® PowerShell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.