Logging in multiple files with Powershell

In this blog post is explained how to write in multiple files using Powershell. To achieve this purpose, we are going to use message streams, which we have already seen in the previous post: do no use write-host cmdlet.

Streams are a fundamental feature in a scripting language that supports piping such as Powershell, especially to avoid that cmdlet receive messages instead of what they really expect. An interesting reading about this topic is: http://blogs.technet.com/b/heyscriptingguy/archive/2014/03/30/understanding-streams-redirection-and-write-host-in-powershell.aspx

In the following sample, we are going to write in different files based on the output type:

  1. Log.txt: Write-Host and the Output stream (Write-Output);
  2. Warning.txt: Warning stream (Write-Warning);
  3. Error.txt: Error stream (Write-Error).

In lines 16 and 18, Write-Warning and Write-Error messages are sent to the Output stream using redirection operators (2>&1, 3>&1). Each stream and all data related to Write-Host, is written in Log.txt file by “*>” operator when is run (line 24).

The trick to write in multiple files is to use the Tee-Object, which saves data in lines 16 and 18 and send it to the specified file.


More about redirection: https://technet.microsoft.com/it-it/library/Hh847746.aspx

More about Tee-Object: https://technet.microsoft.com/en-us/library/hh849937.aspx

2 Responses to Logging in multiple files with Powershell


leave your comment