PowerShell Script to Generate Email Traffic in a Test Lab Environment

For a long time now I’ve wanted to write a script that would automatically generate email traffic within an Exchange Server test lab environment.

Having realistic email traffic within a test lab environment means you can do such real world activities as:

  • test backup and recovery scenarios
  • learn how to use message tracking logs
  • test archiving solutions

In the past I’ve used some simple VBScripts that just sent random messages via SMTP as a way to fill up test lab mailboxes. That approach had some disadvantages though. The scripts I wrote only sent a stream of email messages at a single rate rather than at varying rates through the day as you would see in the real world. They also filled up inboxes only, never putting the messages in the Sent Items folder for the From address.

So I got to work creating a new PowerShell script to generate the email traffic. I tracked some of the development in the forums and can now share the complete script here.

This script does require some setting up before you run it, so please read the instructions to get it working in your test lab. I have only written and tested this script for Exchange 2010 training lab environments on the assumption that most people will be training for the latest version of Exchange.

Before we go further let me be absolutely clear that this script is for test lab environments only. Under no circumstances should you attempt to run this script in a production environment.

Using the Start-MailGen.ps1 Script in Your Test Lab

The scripts uses the Exchange Web Services Managed API so the first step is to download and install that on your test lab server.

EWS Managed API
EWS Managed API

Next, download the script and extract the three files to your server. I placed mine in C:\Scripts\MailGen.

Download the script file here: Start-MailGen.ps1 (downloaded 3090 times so far)

Open the Start-MailGen.ps1 file in the PowerShell editor or in Notepad and check the following items.

The $dllfolderpath variable is set to the default installation path for the EWS Managed API v2.0. If you install a different version, or to a different path, update this variable.

#Path to the Exchange Web Services DLL
$dllfolderpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll"

The script uses a switch statement to determine how many emails to send each hour of the day. These values are what I use but you can change them up or down to suit your test lab. The hours 6am to 7pm are individually specified, and then the default value at the end is used for the remaining hours of the day.

06 {$sendcount = 50}
07 {$sendcount = 80}
08 {$sendcount = 600}
09 {$sendcount = 600}
10 {$sendcount = 800}
11 {$sendcount = 1000}
12 {$sendcount = 600}
13 {$sendcount = 600}
14 {$sendcount = 800}
15 {$sendcount = 800}
16 {$sendcount = 900}
17 {$sendcount = 400}
18 {$sendcount = 200}
19 {$sendcount = 80}
default {$sendcount = 10}

You can just specify even numbers like the above because the script varies the send count further by adding a random number each time. This will give you a realistic level of email traffic through the different hours of the day.

Sample email traffic graph
Sample email traffic graph

The service account that will be running the script needs to have its own mailbox, and also have impersonation rights granted to it. I run mine as Administrator since it is just a test lab. Open the Exchange Management Shell and run the following command to grant the impersonation rights.

[PS] C:\>New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:administrator

You may also need to set your script execution policy to unrestricted.

[PS] C:\>Set-ExecutionPolicy Unrestricted

Also, as the script file was downloaded from the internet you may need to right-click the file and choose Properties, and then click the Unblock button.

The script also depends on the Active Directory remote administration tools. These should be installed already on an Exchange 2010 mailbox server, but if you’re running the script from a non-Exchange server you may need to install them.

Finally, to start generating email traffic open the Exchange Management Shell and run the script.

[PS] C:\Scripts\Mailgen>.\Start-MailGen.ps1

The script begins to send email and will show a progress indicator.

Start-MailGen.ps1 running
Start-MailGen.ps1 running

The script will select a random sender and recipient from the available mailboxes and distribution groups in your test lab environment, and then construct a random email message using the two files that are provided with the script.

After sending the applicable number of emails for that hour of the day the script will sleep for 5 minute blocks until it reaches the next hour, and will start sending again.

You can leave the script running for several days if you wish, or set it as a scheduled task to ensure that it starts up again if the server is rebooted.

How to Hard-Code the EWS URL

A few people have seen Autodiscover errors in their test lab and, if they have verified that Autodiscover is otherwise working fine, may need to look at hard-coding the EWS URL in the script. To do so find the following line and comment it out with the hash character:

#$service.AutodiscoverUrl($user.Properties.mail)

Now add a new line below it with the following:

$service.Url = "https://ho-ex2010-mb1.exchangeserverpro.net/EWS/Exchange.asmx"

Replace the URL above with the appropriate server FQDN for your own server environment.

Comments

  1. says

    Hi Paul,
    Thanks for the info. I will be setting up my test lab this weekend and I will let you know how it goes.

    Cheers.
    TP

  2. kottees says

    Hollo Paul,

    This is the error I’m getting while running.. DC on win 2k3 server and Exch 2010 typical roles installed on win 2008 R2. I could not find the solution for this over the internet.. Please suggest me.
    ************************************************************
    [PS] C:\Paul>.\Start-MailGen.ps1
    WARNING: Error initializing default drive: ‘Unable to find a default server with Avtive Directory Web Services running.’.
    Retrieving mailbox list
    Preparing EWS
    Exception calling “AutodiscoverUrl” with “1″ argument(s): “The Autodiscover service couldn’t be located.”
    At C:\Paul\Start-MailGen.ps1:245 char”25
    + $service.AutodiscoverUrl <<<< ($user.Properties.mail)
    +CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    +FullQualifiedErrorId : DotNetMethodException

    Starting email generation
    *** Will send 615 emails this hour
    Exception calling "SendAndSaveCopy" with "0" argument(s): "The Url property on the ExchangeService object must be set."
    At C:\Paul\Start-MailGen.ps1:245 char"23
    + $mail.SendAndSaveCpy <<<< ()
    +CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    +FullQualifiedErrorId : DotNetMethodException
    *********************************************************

      • Shakti says

        Paul,
        I was getting error when i ran the script on Exchaneg 2013 (CAS + Mailbox) server.
        “Could not establish trust relationship for the SSL/TLS secure channel.”

        Then I installed the certificate but now getting the error

        “The Url property on the ExchangeService object must be set….”
        My server is 2012 R2 hence I don’t have to install “Active Directory Management Gateway Service” as suggested by you above and its not letting me run that update.

        What should I do??

  3. Ifiok says

    Paul,
    Great script – I have been looking for something like this. I have been using this script for the past 2 days and I’m very impressed by the amount of work you put in to generate the script.

    My only comment is this: How about using a text file to log all that information that we “write-host” – For two reasons :
    a) we can review later if we need to, especially if there are errors – this one just scrolls by and we cannot see it anymore.
    b) aslo it frees up screen and runs at the background.
    Just my thoughts.
    Thanks for the sharing it with us.

  4. Raj says

    I am getting this error.
    [PS] C:\Scripts\Mailgen>.\Start-MailGen.ps1
    Retrieving mailbox list
    Preparing EWS
    Exception calling “AutodiscoverUrl” with “1″ argument(s): “The Autodiscover service couldn’t be located.”
    At C:\Scripts\Mailgen\Start-MailGen.ps1:245 char:25
    + $service.AutodiscoverUrl <<<< ($user.Properties.mail)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Running Exchange on DC with Win 2008 R2.

  5. Andrew says

    Hello Paul –
    What could be causing this;

    Exception calling “SendAndSaveCopy” with “0″ argument(s): “The mailbox that was requested doesn’t support the specified
    RequestServerVersion.”
    At C:\Scripts\MailGen\Start-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

  6. Heikal says

    Hi Paul ,

    Create Efforts

    but I got the following error

    Exception calling “SendAndSaveCopy” with “0″ argument(s): “The mailbox that was requested doesn’t support the specified RequestServerVersion.”

    knowing that version of EWSManged API is 1.2

  7. Heikal says

    I successfully solved that error ,I used EWSManaged API version 1.1 instead of 1.2 and your script works fine …the old version (1.1) was not found on Microsoft download center anymore..But got it from “Mike Pfeiffer” Blog “http://www.mikepfeiffer.net/downloads/ExchangeLab.zip” under “bin” folder

  8. Geoff says

    Hi Paul
    I am getting the same error message but I am unsure how to hard code the URL can you help me out?
    Exception calling “AutodiscoverUrl” with “1″ argument(s): “The Autodiscover service couldn’t be located.”
    At C:\Scripts\Mailgen\Start-MailGen.ps1:245 char:25
    + $service.AutodiscoverUrl <<<< ($user.Properties.mail)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Thanks
    Geoff

    • says

      Hi Geoff (and others),

      Firstly I would double-check that Autodiscover is working at all in your test lab. If there is anything wrong with it, or your SSL cert, then try fixing that first.

      Other than that, I am planning to update the script for compatibility with the EWS API v1.2, so I will look to include the manually specified Autodiscover URL option in the next version. Hopefully not far away.

      • Geoff says

        Thanks Paul that helped that problem but now I am having to find out why I am having a permissions/trust Exception calling “SendAndSaveCopy” with “0″ argument(s): “Request failed. The underlying connection was closed: Could not establish trust relationship fo
        r the SSL/TLS secure channel.”

        Some times this stuff makes me pull my hair out.

        Thanks again for your help
        Geoff

  9. Jan says

    Paul this is so cool, i can’t thank you enough for this article en the scripts to put a mail load on a
    lab test environment.

    Very …..very much appriciated was looking for this for quite some time

  10. Gary says

    Nice script, very useful.. Thank you for your time spent.

    I’ve been trying to modify the sender to be able to exclude certain addresses, without much sucess. Any pointers would be appricated.

    Regards
    Gary

    • says

      This line in the script fetches the list of mailboxes to include.

      $mailboxes = @(Get-Mailbox -RecipientTypeDetails UserMailbox -resultsize unlimited)

      So you can just modify that Get-Mailbox any way you like to exclude the ones you don’t want. Help info for Get-Mailbox is here:
      http://technet.microsoft.com/en-us/library/bb123685.aspx

      One way would be to use the -OrganizationalUnit parameter to just get the users in a specific OU, and have the ones you want to exclude be outside of that OU.

  11. Gary says

    Thanks Steve.

    It was that simple!

    Must make note to self to get head round powershell.

    Thanks again.

    regards
    Gary

    • Gary says

      Thanks Paul. (no idea why I typed Steve !, to much Red wine)

      It was that simple!

      Must make note to self to get head round powershell.

      Thanks again.

      regards
      Gary

  12. Eric says

    I’ve made significant progress in getting this script to run in my lab environment. However, I’m now receiving the following error.

    I’m running Exchange 2007 with a Windows 2008R2 DC in the environment. I have worked through several other issues but unable to resolve this one.

    Any assistance would be great appreciated!

    [PS] D:\scripts\mailgen>D:\Scripts\Mailgen\Start-MailGen.ps1
    Retrieving mailbox list
    Preparing EWS
    Starting email generation
    *** Will send 822 emails this hour
    Exception calling “SendAndSaveCopy” with “0″ argument(s): “An element node ‘soa
    p:Envelope’ of the type Element was expected, but node ‘Autodiscover’ of type E
    lement was found.”
    At D:\Scripts\Mailgen\Start-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

      • Eric says

        Paul,

        Thanks for the update. I am one step closer to making this work. The problem that was listed above was because I was pointing to the Autodiscover.xml file and it was looking for the ews/exchange.asmx file. Once I pointed that correctly then it is now giving me the error “Exchange Server doesn’t support the requested version.” and I believe that is because I’m running API v1.2 instead of v1.1. Any assistance on finding or obtaining a copy of v1.1 would be greatly appreciated.

        Eric

        • Phil says

          Eric- did you remember to enable impersonation for the user you are running the script as?

          foreach ($exchangeServer in Get-ExchangeServer)
          {
          if ($exchangeServer.ServerRole -match ‘ClientAccess’)
          {
          Add-ADPermission -Identity $exchangeServer.DistinguishedName -User ‘domain\user’ -ExtendedRights ms-Exch-EPI-Impersonation
          }

          }

          Fixed my headache with exchange 2007 and this script. so far, removing SSL (for a throw away lab, disabling SSL was far simpler), commenting out the exchange.2010 tools, hard coding the services url, and finally giving impersonation permissions to my script user got it all working.

          Great script Paul, thank you very much!

  13. Russ Dillion says

    Paul,

    First, thank you very much for your time and efforts on this. I have been trying to get this working in a test environment for a couple of days now, and am running into an error that I have not been able to solve. I have a 2008 R2 DC, and a 2008 R2 mail server with Exchange 2010 SP1. I believe I have autodiscover configured correctly, and am using the self signed certificate from the Excahnge server. I have added it to the Trusted Root CA store on the server as well. I installed Exchange Web Services Management API version 1.2 as I could not find version 1.1. When I run the script, I am getting the following:

    Retrieving mailbox list
    Preparing EWS
    Starting email generation
    *** Will send 867 emails this hour
    Exception calling “SendAndSaveCopy” with “0″ argument(s): “Exchange Server doesn’t support the requested version.”
    At C:\scripts\Start-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Any ideas?

    Thanks again,

    Russ

      • Eric says

        Does anyone know where I can get a copy of API v1.1? Everywhere i’m looking all I can find is 1.2 or higher. I’ve almost got Exchange 2007 to work but now i’m receiving the same error “Exchange Server doesn’t support the requested version.” I believe with API v1.1 I will have it functioning correctly and will post the changes that were needed in order to make it work.

      • Vikram says

        Hi Paul,

        I am using exchange & outlook 2010, trying to move messages from inbox to Temp folder in the same mailbox.. but I am getting the following error message at line below..

        $Mailbox = “name@domain.com”
        $service.AutodiscoverUrl($Mailbox, {$True}); – This throws an error message..

        Exception calling “AutodiscoverUrl” with “2″ argument(s): “The Autodiscover service could not be located.”
        At C:\ad\MoveItems.ps1:244 char:27
        + $service.AutodiscoverUrl <<<< ($Mailbox, {$True});
        + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : DotNetMethodException

        Please let me to solve this issue.. I am new in dealing with exchange mailboxes.

        Regards,
        Vikram

  14. Mike says

    Hey Paul,

    I executed the following command first and still get the error below. Any idea? By the way, I am using Exchange Web Services Managed API 1.1

    [PS] C:\>New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:administrator

    Exception calling “SendAndSaveCopy” with “0″ argument(s): “The account does not have permission to impersonate the requested user.”
    At C:\Scripts\Mailgen\Start-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

  15. says

    Paul!

    is there a way this script can be modified to target mail enabled public folders? i am trying to prove a point for a customer who has 1000+ public folders and they want to upgrade to 2010!

    • says

      *** I’ll repeat the warning not to use this script in production environments. ***

      On line 236 is the code that determines the mailboxes that are used by the script. You could probably modify that to get mail-enabled public folders instead.

      • says

        its in a demo environment that is no where near the live environment!

        i have tried that but get a long list of errors! it does however pick up the names of the public folders..

        “cannot process argument transformation on parameter ‘Identity’. Cannot convert the “PUBLICFOLDERNAME” value of type “Microsoft.Exchange.Data.Directory.Management.MailPublicFolder” to type “Microsoft.Exchange.Configureation.Tasks.MailboxIdParameter”

        any ideas?

  16. Geoff says

    Hi Paul,
    Well I got the script working and ran it for a bit but let it set for a few weeks and now when I try and run the script I get the following error,
    Get-Random : Minimum (0) cannot be greater than or equal to Maximum (-1).
    At C:\scripts\mailgen\Start-MailGen.ps1:148 char:20
    + $rand = Get-Random <<<< -Minimum 0 -Maximum ($mailboxcount – 1)
    + CategoryInfo : InvalidArgument: (:) [Get-Random], ArgumentException
    + FullyQualifiedErrorId : MinGreaterThanOrEqualMax,Microsoft.PowerShell.Commands.GetRandomCommand

    Thanks
    Geoff

        • Geoff says

          Well Paul, I found my problem. I discovered that I was using the wrong power shell, what a bonehead mistake. its been a long week.
          However I get this new error
          [PS] C:\scripts\mailgen>.\Start-MailGen.ps1
          Retrieving mailbox list
          Preparing EWS
          Starting email generation
          *** Will send 692 emails this hour
          Exception calling “SendAndSaveCopy” with “0″ argument(s): “The request failed. The underlying connection was closed: An unexpected error occurred on a sen
          d.”
          At C:\scripts\mailgen\Start-MailGen.ps1:186 char:23
          + $mail.SendAndSaveCopy <<<< ()
          + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
          + FullyQualifiedErrorId : DotNetMethodException

          Any ideas where I might find why it is getting a send error?
          thanks
          Geoff

        • Geoff says

          Hi Paul
          That is what it appeared to me as well but I can telnet into port 25 and it responds back fine
          Thanks
          Geoff

  17. Brian Flanagan says

    Has anyone tried this script with Exchange 2013? I need to do some load testing with Exchange 2013 and I’m trying to find tools other than loadsim. This tool works great on Exchange 2010!

    Thanks

    • Sam O'Donnell says

      yes! and it works.. well i had to tweak some things..

      i did all of the above, but i was seeing some SendAndSaveAs issues.

      i hashed # out

      #$mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
      #$mail.Subject = $emailSubject
      #$mail.Body = $emailBody
      #$mail.From = $EmailSender
      #[Void] $mail.ToRecipients.Add($EmailRecipient)
      #$mail.SendAndSaveCopy()

      and added this directly underneath

      Send-MailMessage -SmtpServer FRONTENDCAS -From $emailsender -To $EmailRecipient -Subject $emailSubject -Body $emailBody

      it was a long shot but it works..

      Paul, hope you don’t mind :-)

      • says

        That will work but its just sending with SMTP so it doesn’t save the item to the sender’s Sent Items, isn’t as useful for generating test traffic for message tracking etc, doesn’t necessarily use multiple HT’s if available, etc etc. Depends whether you need all that or just the ability to send a bunch of raw traffic around.

        • Chad says

          Paul – do you have a suggestion for how to make this work correctly on Exchange 2013? I did make the changes that Sam suggested and that’s working, but I’d like items to be logged in the sent items if possible. Thanks!

        • says

          I imagine for Exchange 2013 it will be a simple case of using the latest EWS API DLL and updating the script variable that points to the DLL path. But I haven’t had a chance to test that yet.

        • Chad says

          I did get this to work on 2013. I had quite a few issues and saw lots of different errors (most of the ones talked about above and a few more) but they were all issues with my lab…mostly caused by a DNS issue on my DC. After resolving those and undoing all the hacks I was doing to the script trying to get it to work, it works like a champ.

          To get it to work after other issues were resolved, I just had to update the path to the EWS DLL that’s included in 2013 and it does work as expected. Thanks for this awesome script, it’s going to make my 2013 eDiscovery testing much easier.

        • says

          Great, thanks for letting us know. And yes, eDiscovery testing is exactly the type of thing this script is designed to create realistic looking traffic for, so that is awesome :)

  18. Shakti says

    Amazing work buddy!
    Just add impersonation part to the prerequisite in the script itself, rest is awsome!
    Cheers!!!!

  19. Shakti says

    Using this script with slight modification, Is there a way to add attachments from a given set of attachment types (.txt, .doc, .img etc)???

    • Vishwanath says

      Yes You can send attachment

      Add the line under

      $mail.From = $EmailSender
      $mail.Attachments.AddFileAttachment(“full path of the file to be attached”)

      Example
      $mail.From = $EmailSender
      $mail.Attachments.AddFileAttachment(“C:\Users\testexchange\Desktop\email\u_ex110430.zip”)

      save the file and run you should be able to send attachment

      • Shakti says

        one more thing, your suggestion hard codes the attachment file.
        Is there a way the script randomly picks from the set of files from a given folder.
        Say randomly pick any file from the directory C:\Attach.

        • Dave says

          Shakti,

          You could do a lookup to put the list of filenames in the directory into an array and then do a Get-Random against that array to select the attachment for a particular email. If you wanted to get even fancier, you could always do another random true or false to see if a particular email actually gets an attachment or not.

          Cheers

        • Sam O'Donnell says

          Shakti,

          I followed Vishwanath’s advise about the “$mail.Attachments.AddFileAttachment(“C:\Users\testexchange\Desktop\email\u_ex110430.zip”)”

          however I changed it a little!

          I added two new lines to the script,
          $attach = Get-childitem C:\scripts\mailgen\attachments\*.* | Get-Random -Count 1
          obviously change the folder as to where you want to store the attachments, I just have a few pdf. img, mp3, docx files in there.

          above this existing line in the script
          $mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)

          and then I added this line
          $mail.Attachments.AddFileAttachment(“$attach”)

          so my script now looks like this

          $attach = Get-childitem C:\scripts\mailgen\attachments\*.* | Get-Random -Count 1
          $mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
          $mail.Subject = $emailSubject
          $mail.Body = $emailBody
          $mail.From = $EmailSender
          $mail.Attachments.AddFileAttachment(“$attach”)
          [Void] $mail.ToRecipients.Add($EmailRecipient)
          $mail.SendAndSaveCopy()

          Now obviously this will then send attachments to every email it sends, so all have done is modify the number of sending emails, and run the original script to. so I get both lots of emails with and without attachments delivered within the test lab.

          hope that makes sense!

          Sam

  20. Pat says

    Is there any way to find if the attached file is of certain type like xls, jpg, docx, etc, without just looking at the file extension, but by looking at the content-type using ews managed api?

  21. Jon says

    Hey Paul,

    great script, is there a way I could slow the email generation down?

    Having issue when sending large volumes, some of the emails don’t get sent and end up in draft folder of the accounts.

    Cheers

  22. Jarrett says

    Hi Paul,

    I was looking for something like this for testing. Looks exactly like what I need in my test environment. I currently have Exchange 2010 SP1 running on Windows 2008 R2 server. I have the ” Exchange Web Services Managed API 2.0″ installed on the Exchange Server and the script is pointing to the dll “$dllfolderpath = “C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll””

    When I run the script I’m getting the following error each time it attempts to send an email from a user to a user:

    Exception calling “SendAndSaveCopy” with “0″ arguments(s): “Exchange Server doesn’t support the requested version.”
    At c:\generate emails\test email generator\Start-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    +CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    +FullyQualifiedErrorID : DotNetMethodException

    I did try pointing directly to the EWS address instead of using the Autodiscover but I continue to get the error message.

    The problem seems to be on line 186 of the code "$mail.SendAndSaveCopy()". If I comment this out the script does seem to run successfully but no emails are actually sent. It just appears to go through the motion of sending emails.

    Any help you can give would be greatly appreciated.

    Thanks!

    • says

      I ran into this issue myself and I can’t remember what exactly was the the cause. I think it was the version of the EWS API needing to be an earlier one (1.x would probably work fine with Exchange 2010 SP1).

      So you could try some of the older API versions, or upgrade the Exchange server to 2010 SP3 which should work with API version 2.0 AFAIK.

      • Jarrett says

        I was actually able to get it working by adding the Exchange Version to the following line in the code:
        $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService(“Exchange2010_SP1″)

        I found this in the subscriber comments above.

        There is another tech in my office who is having some issues as well but we believe its related to his test exchange server and impersonation rights. He’s rebuilding that server and we hope to get it up and running on his by next week.

        Thank you for your help!

  23. Eugene says

    Hi

    Had the same error for “Exception calling “SendAndSaveCopy” with “0″ arguments(s): “Exchange Server doesn’t support the requested version.””.

    Ran Exchange 2010 SP3 on Server 2012. Installed API version 2.0.

    Changed the following in the script and errors was gone.

    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService(“Exchange2010_SP2″)

    Tried SP2 although it was SP3 and it worked.

  24. Dan says

    Paul,

    Great script as I got it to run in my Exch 2007 test environment. Is there a way to get this script to run continuously and not wait for the next hour? Additionally, I think I know how to increase the amount of emails generated but want your input….What I’m testing in Dev is to generate many tracking logs for our Arcsite environment.

    Thanks,

    Dan

  25. Brian says

    Hey all,

    Can’t wait to work with this script, however I receiving the following error when I try to run the script.

    I have EWS Managed Api 1.2 installed. Exchange 2010 SP3

    Exception calling “SendAndSaveCopy” with “0″ argument(s): “The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”
    At C:\Users\bashipman-adm\Desktop\Mailgen\Start-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Thanks,
    Brian

    • Brian says

      Fixed that issue…

      http://blogs.technet.com/b/sbs/archive/2007/04/10/installing-a-self-signed-certificate-as-a-trusted-root-ca-in-windows-vista.aspx

      Now running into:

      Exception calling “SendAndSaveCopy” with “0″ argument(s): “An element node ‘soap:Envelope’ of the type Element was expected, but node ‘Autodiscover’ of type Element was found.”
      At C:\Users\bashipman-adm\Desktop\Mailgen\Start-MailGen.ps1:186 char:23
      + $mail.SendAndSaveCopy <<<< ()
      + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : DotNetMethodException

      • Brian says

        Tried to fix the issue by disabling all authentication methods on the Autodsicover virtual directory except Basic and received.

        Exception calling “SendAndSaveCopy” with “0″ argument(s): “The request failed. The remote server returned an error: (401) Unauthorized.”
        At C:\Users\bashipman-adm\Desktop\Mailgen\Start-MailGen.ps1:186 char:23
        + $mail.SendAndSaveCopy <<<< ()
        + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

        Then I tried just Windows Authentication (Disabled Basic and Anonymous) and received:

        Exception calling "SendAndSaveCopy" with "0" argument(s): "The response received from the service didn't contain validXML."
        At C:\Users\bashipman-adm\Desktop\Mailgen\Start-MailGen.ps1:186 char:23
        + $mail.SendAndSaveCopy <<<< ()
        + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

        • vishwanath says

          Hi,

          the user running the power shell should be mailbox enabled and should have full access to all mailbox.
          Unless the user does not have full access to mailbox it fails to save the copy
          the user should have impersonationAssignmentName role assigned
          under #Web services initialization
          you need to set the $service.URL to https://casserver /ews/exchange.asmx

  26. Dave says

    Paul,

    Great script, I’m using it pretty much out of the box on Exchange 2013 CU3 on Windows 2012 and EWS API 2.0 (changed the path in the script to point to the proper DLL)

    One thing I did notice was that the last mailbox (user name of Zena), never sent or received email. Basically it was part of this line in your script:

    $rand = Get-Random -Minimum 0 -Maximum ($mailboxcount – 1)

    If you look at the TechNet article for the Get-Random command (http://technet.microsoft.com/en-us/library/ff730929.aspx), it states that the maximum must be 1 more than your desired maximum:

    “And yes, -maximum must always be set to 1 more than the high number in the range. That means that, to select a random number between 1 and 100, we must set –maximum to 101; if we set –maximum to 100 then we’d actually select a random number between 1 and 99. ”

    By subtracting 1 from $mailboxcount, the last mailbox would never be used. I changed the line and removed the -1 and the last mailbox is now sending and receiving email.

    Thanks again, this is fantastic. I’m busy loading up my mailboxes across six databases to test auto reseed :)

  27. Jerry says

    First, this is AWESOME for labs. Just fantastic. I’m so happy I don’t have to run LoadGen 24×7 :)

    A little about my experience:
    I created a whole new account to do this with in the lab. On the first run, it only found one recipient, which took me a while to realize, it only found it’s own mailbox. Get-mailbox only returned itself! Woops!

    I added the account I use “SMTP Test” to the Exchange Recipient Management RBAC Group. Which solved the problem! Now it’s just chugging away.

  28. sm00th says

    Hi,

    First of all, this is a kickbutt script! Thank you so much.

    Now, my question is, is there a way to SPECIFY the email recipients? Not just random? Here’s the thing, I need to stress test my Exch 2010 servers in PROD. A little backstory first, I’m in the middle of migrating from Exch 2007 to Exch 2010. Right now both Exchange 2007 and 2010 are coexisting but I have not cutover yet. Everything flows to Exch 2007 first, then if the email is intended for an Exch 2010 mailbox then it send it to the Exch 2010 mailbox.
    Before I actually move all users from 2007 to 2010, I need to make sure my Exch 2010 Mailbox servers can handle the load (it’s a physical server with local attached disks).

    If I run this script, it’s going start spamming random Exch 2007 users, and I don’t want that… well, at least I don’t want to be here when that happens :-)

    Any help is greatly appreciated.

    Thanks again!

    • says

      I don’t recommend using this script in any production environment (or any script like it for that matter). It is not intended to be used to validate a hardware/storage design.

      If you’ve sized your server and storage hardware based on the Exchange 2013 sizing calculator that Microsoft published, and you want to validate that, then Microsoft also has tools such as Jetstress for that task.

  29. Aorta says

    Hi Paul,

    I am trying to run the script in an Exchange 2013 environment from a Win 7 machine running PS 3.0 and all the prerequisites you mentioned in the blog but I get the following errors :

    Exception calling “SendAndSaveCopy” with “0″ argument(s): “The Id property must be set.”
    At C:\Users\sa-exc-imp\Desktop\Start-MailGen1\Start-MailGen.ps1:296 char:26
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    *** New email message
    Cannot process argument transformation on parameter 'Identity'. Cannot convert value "TA_Alain Struillou" to type "Micr
    osoft.Exchange.Configuration.Tasks.MailboxIdParameter". Error: "Cannot convert hashtable to an object of the following
    type: Microsoft.Exchange.Configuration.Tasks.MailboxIdParameter. Hashtable-to-Object conversion is not supported in res
    tricted language mode or a Data section."
    + CategoryInfo : InvalidData: (:) [Get-Mailbox], ParameterBindin…mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Mailbox

    You cannot call a method on a null-valued expression.
    At C:\Users\sa-exc-imp\Desktop\Start-MailGen1\Start-MailGen.ps1:232 char:31
    + if($SenderSmtpAddress.GetType <<<< ().fullname -eq "Microsoft.Exchange.Data.SmtpAddress") {
    + CategoryInfo : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Sender:
    Subject: Stygian adamant ossify
    Cannot process argument transformation on parameter 'Identity'. Cannot convert value "Astruill Microsoft" to type "Micr
    osoft.Exchange.Configuration.Tasks.RecipientIdParameter". Error: "Cannot convert hashtable to an object of the followin
    g type: Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter. Hashtable-to-Object conversion is not supported in
    restricted language mode or a Data section."
    + CategoryInfo : InvalidData: (:) [Get-Recipient], ParameterBindin…mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Recipient

    You cannot call a method on a null-valued expression.
    At C:\Users\sa-exc-imp\Desktop\Start-MailGen1\Start-MailGen.ps1:272 char:38
    + if($RecipientSmtpAddress.GetType <<<< ().fullname -eq "Microsoft.Exchange.Data.SmtpAddress") {
    + CategoryInfo : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Recipient:
    Exception calling "Add" with "1" argument(s): "Object reference not set to an instance of an object."
    At C:\Users\sa-exc-imp\Desktop\Start-MailGen1\Start-MailGen.ps1:282 char:35
    + [Void] $mail.ToRecipients.Add <<<< ($EmailRecipient)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Cannot process argument transformation on parameter 'Identity'. Cannot convert value "sa-exc-imp" to type "Microsoft.Ex
    change.Configuration.Tasks.RecipientIdParameter". Error: "Cannot convert hashtable to an object of the following type:
    Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter. Hashtable-to-Object conversion is not supported in restric
    ted language mode or a Data section."
    + CategoryInfo : InvalidData: (:) [Get-Recipient], ParameterBindin…mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Recipient

    You cannot call a method on a null-valued expression.
    At C:\Users\sa-exc-imp\Desktop\Start-MailGen1\Start-MailGen.ps1:272 char:38
    + if($RecipientSmtpAddress.GetType <<<< ().fullname -eq "Microsoft.Exchange.Data.SmtpAddress") {
    + CategoryInfo : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Do you have an idea why this might happen ?

    Thanks

      • Aorta says

        Hi Paul,

        Thanks for replying to my post :)

        I finally managed to solve the issue by installing the Exchange 2010 Management Tools on the workstation and hardcoding the EWS to an Exchange 2010 server.

        In fact the first time i did modify the script in order to import the PSSnapin for Exchange 2013 as this would fail with unable to load any snapin… I think this was causing the issue…

        Thanks for a great script Paul and i hope this will help others running into the same issue.

  30. Justin says

    Paul, this is awesome. Do you know if there is a way to set PermissionControlled through EWS Managed API? I have looked around without much luck, but I was hoping to introduce some protected content into the test also to see how the Journal Decryption agent affects performance.

    • says

      No idea to be honest. The EWS API is pretty well documented on MSDN or I would suggest posting in the Exchange Developers forum on TechNet or checking Glen Scale’s blog to see if he has any tips for that.

Leave a Reply

Your email address will not be published. Required fields are marked *