Friday, February 17, 2012

Redirecting output of PowerShell scripts

Now I have finished creating the first part of my PowerShell script, and I now want to create some sort of logging instead of just having the output printed on the console. So I need to redirect the output to a log file, and still see on the console what is being written to the file.

To achieve this, I used  Tee-Object as shown below. This will redirect even the error messages to the log file and continuously display the contents of the file as it is written to.


     ./samplescript "input parameters" 2>&1 | Tee-Object  "logfile.txt"


To redirect just the output to the log file and leave error messages to the console:


     ./samplescript "input parameters" > "logfile.txt"

Here are the other Windows PowerShell redirection operators:

Operator Description Example
> Redirects output to the specified file, overwritting its current contents. ./samplescript "input parameters" > "logfile.txt"
>> Appends output to the current contents of hte file. ./samplescript "input parameters" >> "logfile.txt"
2> Sends errors to the specified file. Overwritting its current contents. ./samplescript "input parameters" 2> "errorfile.txt"
2>> Appends errors to contents of the specified file. ./samplescript "input parameters" 2>> "errorfile.txt"
2>&1 Sends error messages to the success output stream ./samplescript "input parameters" 2>&1 "logfile.txt"


Reference: http://technet.microsoft.com/en-us/library/dd315283.aspx

*joychua97

No comments:

Post a Comment