PowerShell: Transcript script output with newline

Recently I was searching for an easy way to log all output from my PowerShell script. This was a relatively low priority requirement so I’ve figured that if I won’t find an easy solution to this quickly, than I will drop it.

It turns out, that there is an easy way to do this. It’s called Transcript. It’s activated with Start-Transcript and deactivated with Stop-Transcript.

Transcript works only in the console, so if you are running your script in any IDE (Windows Powershell ISE for example), you will get an error. To avoid this, you can use code that looks like this:

if($host.name -eq 'ConsoleHost')
{
   Start-Transcript -Path "C:\Path\To\MyTranscript.txt" -Append
}

This will start the transcript feature only if the current script is executing in the console context.

To stop the transcript we can similarly use:

if($host.name -eq 'ConsoleHost')
{
    Stop-Transcript | Out-Null
}

The Stop-Transcript command normally produces a message. If you don’t want to see this message you can pipe the result to Out-Null.

There is another problem with this script. If you would look into the file that you are transcribing into, you would notice, that all of the output is in one “block”. This is because Transcript simply ignores empty Write-Host commands. This can be a problem if you want a human to read your transcript.

If your file is not too big, and you this is not a critical feature, you can use a hack to make it right:

if($host.name -eq 'ConsoleHost')
{
    Stop-Transcript | Out-Null

    $logContent = Get-Content $userRemoteLogDateiPath
    $logContent > $userRemoteLogDateiPath
}

Here we are reading the transcript, and writing the output once again into the file. This will produce our transcript with proper new lines.

This is a hack though and should only be used in simple situations with small files, because processing a big transcript like this could really affect your script performance.

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 1 = nine

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>