E235
E235

Reputation: 13500

How to redirect errors to a variable

I have a script that pass over files and I want to redirect any errors to a variable and print them in the end of the script.
Here is example for a problem I am getting:

 Get-ChildItem C:\Windows\appcompat -Recurse | ForEach-Object {
            # do stuff ...
        }

Sometimes there are folders that I don't have access to them and it throws exception:
enter image description here I know how to ignore these errors and continue using the switch -ErrorAction, but I wanted to collects all the folders that I don't have access and print them in the end of the script.

With redirection it is possible to use 2> which will redirect the errors to a file:

 Get-ChildItem C:\Windows\appcompat -Recurse 2> errors.txt | ForEach-Object {
    # do stuff ...
}

Is it possible to redirect, only the errors, to a variable and then I will print them in the end of the script ?

Upvotes: 1

Views: 560

Answers (1)

mklement0
mklement0

Reputation: 440337

You can use the common -ErrorVariable parameter to collect a cmdlet's errors in a variable.

Since this collecting happens in addition to errors getting sent to the error stream, as usual, you must explicitly silence the error-stream output with 2>$null if you want the collecting to be silent.

Therefore, in order to silently collect errors in, say, variable $errs, use the following:

# Shorter equivalent of `-ErrorVariable errs`: `-ev errs`
Get-ChildItem C:\Windows\appcompat -Recurse -ErrorVariable errs 2>$null | ForEach-Object {
            # do stuff ...
}

Note:

  • The short alias name for -ErrorVariable is -ev

  • Be sure not to prefix the target variable name with $ - you're passing its name, not its value.

  • Do not use the name Errors, because $Errors is the automatic (built-in) variable in which all errors that have occurred in the session are being collected.

  • The target variable receives a collection of type [System.Collections.ArrayList] containing [System.Management.Automation.ErrorRecord] instances.

    • Note you get a collection even in the case of only a single error having occurred, which may be surprising, given that PowerShell usually unwraps single-element collections; this surprising behavior is discussed in this GitHub issue.

Unfortunately, this convenient error-collecting mechanism is not available when calling external programs (e.g., when you call git), because such calls do not support common parameters; however, there is a suggestion on GitHub to introduce an alternative syntax.

Upvotes: 3

Related Questions