Redirecting Output with Windows PowerShell
Often you’ll want data sent to a file. Windows PowerShell includes several redirection operators.
Operator and Example | Description |
---|
> Command > filename PS C:\> get-help about_execution_policies > exec.txt
| Sends output to a file. The file is created if it doesn’t exist and overwritten if it exists. |
>> Command >> filename PS C:\> get-help about_execution_policies >> about.txt
| Appends output to a file. Existing data is not overwritten. |
2> Command 2> filename PS C:\> get-help about_execution_polic 2> errors.txt
| Sends errors to a file. If there aren’t any errors, the file is blank.
Note
The command fails and gives an error output because the last three letters (ies) in about_execution_policies are missing.
|
2>> Command > filename PS C:\> get-help about_execution_polic 2>> errors.txt
| Appends errors to a file. Existing data is not overwritten.
Note
The command fails and gives an error output because the last three letters (ies) in about_execution_policies are missing.
|
Understanding PowerShell Errors
PowerShell provides excellent feedback when you make
an error. However, unless you know what to look for, it can look just
like a huge red blob.
Note
Errors are in red text on a black background and clearly indicate something is wrong with the previous command.
Figure 1 shows an example of what an error looks like, and the error is explained in the following table.
Operator and Example | Description |
---|
Command with an error:
PS C:\ > get-service | getmember
| This command is missing the dash (-) between get and member. It results in an error. |
First part of error message:
The term 'getmember' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and
try again. | The first line indicates what isn’t understood. In this case, getmember is not understood because it’s missing the dash. It should be get-member. |
Second part of error message showing location:
| This
gives the specific line number and character number where the error was
encountered. In this case, it gives the character number where the
unknown command (getmember) ended.
Note
Most commands are on line 1, but if you’re running a script, this tells you which line of the script is at fault.
|
Third part of error message pointing at error:
+ get-service| getmember <<<<
| The <<<< characters are arrows or pointers to the offending command. In this case, the arrows point directly at getmember. |
Additional information:
+ CategoryInfo : ObjectNotFound: (getmember:String) [], CommandNotFoundException
| The
error closes with some technical information. If you’re writing a
script, this can be useful, but usually, the first lines give you the
information you need to resolve the problem. |