08 April 2008

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 Documents\WindowsPowerShell\Microsoft.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
Filed under:
 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker