How to use Start-Transcript in the Powershell

Scripts are very helpful and can automate lot of our daily tasks. However, most of times we have the request to keep logs of the script that we are running. Logs can give us to understand what tasks was run, if it's failed , and info that can help us to troubleshoot.

Powershell has lot of commands that can give us logs and exported to a file. Today i would like to explain how can use the command Start-Transcript to track everything from the time that a PowerShell Script will start until finish.

Let's start !!!

The Start-Transcript writes everything in your session when you are run a script in a log file. It's straightforward to use it with a couple of parameters.

Let's use a simple script as example for this article.

I am using the -WhatIf parameter to have only the results when the script  running to use it multiple times

 

Append and No Clobber

Let's see how can use these parameters.

With the -Append we can use the same file to log the actions without overwrite it. You can use this parameter if you want to keep the Logs in a single file.

 

 

With the -NoClobber it's not allow to write the logs in the same file, and will be failed if will try to write in the same file.

 

 

Path and OutputDirectory

For the location of your logs you have two parameters.

With the -Path we must specify the full path including the filename. This is usefull when you want to have a single file of your logs file.

 

With the -Outputdirectory we must specify only the path of the folder. The cmdlet will generate the unique filename.

The filename will be  something like in the printscreen.

 

 

IncludeInvocationHeader and UseMinimalHeader

By default the transcript use the parameter -IncludeInvocationHeader which logs the file with a Full Header include lot of details like time, PSVersion, Host,etc. 

The details that the Header include are lot but sometimes might be useful to keep it.

This is the time header when you are using the -IncludeInvocationHeader.

 

However , from PowerShell 6 and after we can use the parameter -UseMinimalHeader which logs only the Start and End Time of the script.

This is the time header when you are using the -UseMinimalHeader.

 

How to include the Start-Transcript in the Script

If you want to include the Start-Transcript in the script you must include your script between the Start-Transcript and Stop-Transcript.

Let's see the example here:

Start-Transcript -Path c:\scripts\logs.txt -UseMinimalHeader

      Remove-Item -Path C:\Users\Administrator\AppData\Local\Temp\* -Recurse -Verbose -WhatIf

Stop-Transcript

 

 

The Start-Transcript it's a very useful command when you would like to keep logs for your scripts which run manual or scheduled.

However ,don't forget that it's only for keeping logs and not for error handling.

 

If you have any question just drop a comment below or in Twitter  and  Facebook.

 

Disqus Comments