Can you send that to me in an email?

Sometimes I’m writing Powershell scripts to gather information on a seemingly ad-hoc basis and then someone says; "Oh, and can you send that to me in an email every day|week|month". These scripts would often use a bunch of Write-Host statements to output to the console. Modifying these to send the output in an email can be time consuming. That is, unless you know about the Start-Transcript cmdlet.

The Start-Transcript cmdlet will record all console output to a text file. It’s a snap to stick into any existing scripts.

Start-Transcript -Path "$env:USERPROFILE\output.txt";
# All output from here is logged to a text file...
Write-Host "I'm starting my transcript file...";
Get-Date -Format "yyyy-MM-dd hh:mm:ss";
Get-Service -Name "*sql*";
Write-Host "Finishing transcript session.";
Stop-Transcript; # Stop transcription
Write-Host "My transcript has finished..."; # Not output to file

This will display any output as normal in the console.

Powershell Start-Transcript cmdlet

Additionally a text file, called output.txt, will be generated in your user profile directory (C:\Users\Rhys on my laptop).

Windows PowerShell Transcript Start
Start time: 20101221212045
Username  : rhys-VAIO\rhys 
Machine	  : RHYS-VAIO (Microsoft Windows NT 6.1.7600.0) 
Transcript started, output file is C:\Users\rhys\output.txt
I'm starting my transcript file...
2010-12-21 09:20:45

Status   Name               DisplayName                           
------   ----               -----------                           
Running  MSSQL$SQLEXPRESS   SQL Server (SQLEXPRESS)               
Stopped  MSSQLServerADHe... SQL Active Directory Helper Service   
Stopped  MySQL              MySQL                                 
Running  MySQL51            MySQL51                               
Stopped  SQLAgent$SQLEXP... SQL Server Agent (SQLEXPRESS)         
Stopped  SQLBrowser         SQL Server Browser                    
Running  SQLWriter          SQL Server VSS Writer                 
Finishing transcript session.
Windows PowerShell Transcript End
End time: 20101221212045

Then all you have to do is send an email with Powershell including the output file as an attachment or body content. Happy days!

One Comment

  1. Mike says:

    This is perfect for a project I am working on., Thanks

Leave a Reply