Automatically Email PowerShell session transcript

How about automatically logging your entire PowerShell session and getting the transcript in an email ?

You can use it to keep a track of changes made (of course via powerShell :)) Or just for logging.

PowerShell can be customized via Profiles. The profile is loaded every time a Windows PowerShell window is started. You can create one for your account by running

new-item -path $profile -itemtype file -force

It will actually create a file My DocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1

Open it up

notepad $profile

and add the following code to it

################################################################
# Auto Email Transcript #
################################################################

$logfolder = "C:Temp"
$logname = Get-Date -f "dd-MM-yyyy-hh-mm-ss"
$logpath = $logfolder + $logname

function Begin-Transcript
{

if(Test-Path $logfolder)
{
Start-Transcript $logpath -append -force
}
}

Begin-Transcript

function Email-Transcript
{
$message = New-Object System.Net.Mail.MailMessage
$message.From = "user@example.com"
$message.To.Add("user@example.com")
$message.Subject = "PowerShell Transcript $logname"
$message.Body = Get-Content $logpath

$smtp = New-Object System.net.Mail.SmtpClient
$smtp.Host = "smtp.example.com"
$smtp.UseDefaultCredentials = $true
$smtp.Send($message)
}

function Bye
{
Stop-Transcript
Email-Transcript
Remove-Item $logpath
exit
}

################################################################

Its a simple script all I do is generate a filename and pass it to Start-Transcript. Once the PowerShell window is closed the Bye function is triggered. It runs Stop-Transcript which stops the logging and then emails the file using the Email-Transcript function.

If you do not want the log in an email but just want to leave the transcript on the server you can comment the Email-Transcript / Remove-Item lines. Also change the $logfolder variable to a folder where you want to store the session.

If you want to log what all the users are doing using PowerShell on a server you can add this to the Machine-Wide profile file. Just ensure you add an Outlook Rule to filter out the emails :)

Bookmark and Share