A Quick PowerShell Tip (redirecting the output of a PowerShell script)

by sharepointbitme

If you have been to this blog before you may have seen my SharePoint 2013 preupgradecheck script. One thing that always bothered me about that script was that I had to ask the user to redirect the output when they ran the script by using the out-file cmdlet, like this:

Open the SharePoint 2010 Management Shell and type:
c:[directory where you placed the script]InfoScript2010.ps1 | Out-File -width 200 c:InfoOutput.txt

I kept thinking there had to be a better way to redirect the output from within the script itself, but I never really took the time to come up with a solution until recently. After sitting and really thinking it over for a few minutes instead of just complaining I found a simple answer that I thought I would share here, even though it isn’t really about SharePoint.

A nice  feature in PowerShell is the function, simply put simply, a function is just a block of code that you have wrapped up so you can use it later in your script. For example:

function sayHello
write-output "Hello, how is your day?"

After creating this function in your script you can call it at any time by just using sayHello as a command and everything within the  brackets { } will execute. This is great for pieces of code that repeat, or that need to be run under different conditions, but it turns out it is also an easy way to redirect output. For example, if you have the function above in your code you can redirect the output to a file very simply.

sayHello|Out-File c:hello.txt

So with my preupgrade check as an example, I could just enclose the entire script inside a function called outRedirect and then pipe that into the file I want.

function outRedirect
(the entire script found here)

outRedirect|Out-File -width 200 c:InfoOutput.txt

As with most of my PowerShell advice, this isn’t exactly rocket science, but I like to share and I hope it is useful to you.