Log Messages from a Command in PowerShell

Objective

When we run a cmdlet directly in PowerShell, any error, warning, or info regarding the same gets displayed in the console.

Here, I also want to capture the same messages but while running a ps1 script so as to log them down in a separate file. Since, I’ll schedule the script to always run on machine startup, cmdlets like, Start-Transcript & Stop-Transcript won’t be of any help as I’ll have to run the script in -NonInteractive mode of PowerShell.

Why -passthru

Before getting into the solution part, I’d first like to talk about the Powershell parameter, -passthru. -passthru is for the cmdlets that do not return any data. Here, in the current example, I am using the the cmdlet, start-service to start a windows service. By default, it does not return anything and silently continues except, for errors. If I add -passthru parameter to this cmdlet then, a service object is returned containing all the details of the service upon which the cmdlet is executed. Now I can use this object to track the status of the service and consequently log them down.

Solution

So -passthru will return the object which in turn I can use for logging. However, I still need to redirect this output to a file. To do that, I’ll run the following cmdlet

start-service SPTimerV4 -passthru *>&1

This will return the stream which can be easily redirected to a file. Mission accomplished!

Explanation

*>&1 is a Windows PowerShell redirection operator which sends all output types (*) to the success output stream, So weather the command resulted in an error or it ran successfully, every thing is now getting captured and subsequently logged down.

There are other redirection operators as well. They are defined in the following technet article,
https://technet.microsoft.com/en-us/library/hh847746.aspx

Advertisements