Don’t send too many emails

So this might sound obvious but it’s easy to send an email using PowerShell so a corollary is that if you don’t put limits into your scripts you could send a lot of email!

I used a working function in a new script to save time and this is good practice isn’t it to reuse code you have already written and tested.

Unfortunately the script that called the function was sending the wrong information so the net result was my script sent lots and lots of debug messages.  Not cool!

When I write scripts that automate updates in AD I always put limits in so that should an unexpected event happen the script doesn’t destroy my AD environment and I do mean destroy, automation is a double edged sword get it wrong and you can end up doing really bad things so just in case I ALWAYS put limits in so that a script will not do more than an expected number of updates.

Sending 1000s of emails might not be as destructive but clearly it’s not right so I’ll be adding something like this to any function that can send emails from now on.

if ( ! ( Test-Path variable:script:maxEmailLimit ) ) {
$script:maxEmailLimit = 10
if ( ! ( Test-Path variable:script:emailsSent ) ) {
$script:emailsSent = 0

The point of this blog is also to bring up another technique I use related to variable scope. You can create variables anywhere in your script with scope script.  This means you can call a function that can create variables that will not disappear once the function completes.  Remembering how many emails you sent already is a good example of using this.

The Test-Path checks if I have already created a variable and if not I create it with scope script which means all my other functions will have access to the variable too, in case I have more than one function that can send emails.

Then before sending any emails I compare $script:emailsSent with  script:maxEmailLimit and if I’ve already sent too many emails my script will send a diagnostic email to me telling me I breached the limit and will then stop sending emails – You can decide if the script should continue or fail gracefully depending on your application.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.