Friday, May 24, 2013

Output to multiple destinations in PowerShell

Sometimes you need to output a result of a Cmdlet execution or a variable to screen and a file, for example if you want to log all operations in a script in addition to showing the output to the user.
Calling both Out-Host and Out-File for each operation is clearly not a good option.
The nice Tee-Object Cmdlet can perform this functionality, but till before version 3.0, it cannot append output to an existing file. So be it, I have to code it:

function Out-All([string]$FilePath, [switch]$Append)
        if($Append -eq $False)
            New-Item -Path $FilePath -ItemType File -Force
        $_ | Out-Host
        $_ | Out-File -FilePath $FilePath -Append

The above function writes the pipline input to both a file using Out-File and screen (or whatever taking the output) using Out-Host. The advantage is that it has the Append  switch.
The Begin block which executes before processing the pipline data checks  the Append switch and creates a new file (or not) accordingly.
The Process block is responsible for the actual writing of data.

Sample use:

(1..100) | Out-All -FilePath "C:\log\data.log"

(1..100) | Out-All -FilePath "C:\log\data.log" -Append

dir | Out-All -FilePath "C:\log\data.log" -Append

No comments: