PowerShell, Write log and email

One of the key components to many of my scripts is to have it produce either a transcript or CSV or both and send out an email with that attached. You can take and modify this code to make files for input into a Database or to simply send out a “I ran a script” email.

So first we’ll have to produce a file of data. I’ll start with an output of the PowerShell transcript. Most scripts run under a non-user account and we can use it’s Documents section as the file repository. We’ll add the Start-Transcript command and then use the Get-Date command to set a time stamp. In this example I’ll leave the default Get-Date format however there are certainly times and places to modify its format; which we’ll visit later in another post.

As is, the file will be created in the C:\Users\Username\Documents folder.

Then run whatever group of commands you want output from. Perhaps Office 365 for licencing new users, Exchange for creating new mailboxes, Active Directory to check password changes, and the list goes on. I’ve used this command for each of those scenarios and I’ll post some additional code and blogs about them in the future. Once you’ve finishing doing what ever it is you need to close out the transcript with a time stamp for when it was completed.

Next pickup the transcript file by selecting only the last one file on the server in the script accounts documents folder. Then send out an email with two recipients and attached the transcript file.

Of course this assumes you have your own local SMTP server to accept outbound emails and that it will trust the from email address or the IP of your server.

Thanks and hope this helps.