Your basic ITPro blog... What's going on at work, what I'm interested in.

Monday, July 13, 2009

Powershell and E-mail

There are times when I need to notify a group of people of a change made on our network file system. Perhaps the contents of the folder has changed and I need to let everyone who has access to that folder know. Perhaps permissions to a folder has changed (someone has been added or removed) and I want to notify everyone with rights to the folder.

This is normally an annoyingly manual process. Cull names from the security tab and generate a list of people, then paste them in to a mail message, etc… you get the idea.

So, I decided I would see if I could write a Powershell script to do the heavy lifting for me. Specifically, I want my script to:

  • Gather the e-mail addresses of everyone with access to a shared folder
  • Create an e-mail message and address to these people
  • Save this message in my Drafts folder for further processing

Really a simple task, but, if automated, will save me tons of time.

The script is not yet written, but I have the basics down. Of course, it is ridiculously simple with PowerShell (and the Quest AD Cmdlets)

Here is the basic framework I have thus far…

# Get Email address of group members
$addrs = Get-QADGroup <GroupName> | Get-QADGroupMember | select email

$ol = New-Object -comObject Outlook.Application

$mail = $ol.CreateItem(0)

#Address mail
foreach ($addr in $addrs)

$mail.Subject = "Some Subject"
$mail.Body = "Some Body"

#Save to drafts

As you can tell, there is a lot of work yet to do. Input, validation, etc., etc.  But, in just a few lines of code, this script is already performing tasks that would take me minutes to do. I love how easy it is to access AD objects and COM objects and pass data back and forth.


Anonymous said...

Any ideas on how to add a variable to the email body ?

I have a script that processes a third party csv file and AD information. The csv file contains information on when their remote access tokens expire. I would like to use this date in the email body.

Derek Mangrum said...

The easiest way, I think, would be to create the body of the e-mail in a variable.

$body = "This is the body of the email, including the date, which is $(Get-Date)"

You can pass any variable, cmdlet, etc. into this.

Then, just use the $body var in the $mail.Body = statement.

$mail.Body = $body

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332