PowerShell: Create Exchange Mailboxes For AD Users (Update 1.6)

Recently I needed to write a PowerShell script to create Exchange mailboxes for new users in Active Directory. The script needed to create the mailboxes, use different databases, retention policies, and take users from several Organisational Units along with users in child OUs.

This script is also available to download from the Microsoft TechNet Script Center and the PowerShell Gallery.

 

Features and Requirements

  • This script is designed to be run locally on an Exchange Server.
  • The Exchange Server management tools must be installed.
  • The Active Directory management tools must be installed.

This script has been tested on Windows Server 2016 with Exchange 2016, and Windows Server 2008 R2 with Exchange 2010.

When running the script from command prompt or as a Scheduled Task the -file parameter should be used, here’s why:

The -file Parameter And Why It Matters

When running a PowerShell script from the command prompt or as a Scheduled Task without the -file parameter, any user defined parameters which contain spaces, must be surrounded by ‘single quotes’ as using “double quotes” doesn’t result in the script seeing the parameter as a complete string. When running a PowerShell script with the -file parameter, the “double quotes” work as expected. Cue “The More You Know” GIF.

With this in mind, when running the script please use the -file parameter and surround any database & retention policy friendly names “double quotes” if they have spaces. Also the Distinguished Name for the OU you wish to query for users should be surrounded by “double quotes” also because PowerShell will remove the comma’s from the string.

Generating an encrypted password file

If you’ve used a previous version I’ve changed how the script handles configuring a password for the log notification e-mail. Specifically the password must now be in an encrypted text file. The advantage of this is that the password will no longer be in plain text, which is a security risk. The downside is that you will now need to generate a password file. The command to do this is pretty simple, but it must be generated on the computer the script will be running on, and as the user used to run the script.

To generate the password file, run the following command in PowerShell. When running the command you will be prompted for a username and password. The username doesn’t matter and can be anything, but the password must be the password you want to use to authenticate to your SMTP server.

$creds = Get-Credential
$creds.Password | ConvertFrom-SecureString | Set-Content c:\scripts\ps-script-pwd.txt

After running the commands, you should have a text file contained the encrypted password. Enter the path and filename for the -pwd switch to configure authenticated e-mail notification.

Configuration

As with my previous scripts I’m using command line parameters to configure the script, here’s the possible configuration switches.

Command Line Switch Mandatory Description Example
-ou Yes Enter the DN (Distinguished Name) of the OU that you wish to search for users. The DN must be surrounded by “double quotes.” “ou=Staff,dc=contoso,dc=com”
-datab Yes Enter the friendly name of the database you wish to create the mailboxes in. If the name has spaces, please surround it with “double quotes”. Mail-DB-1 OR “Mail DB 01”
-rp No If you wish to set a retention policy for the new mailboxes, specify the friendly name here. As with the database, if the name has spaces sourround it with “double quotes”. Retention-Policy-01 OR “Retention Policy 01”
-l No Location to store the optional log file. The name of the log file is automatically generated. E:\scripts
-sendto No The email address to send the log file to. me@contoso.com
-from No* The email address that the log file should be sent from.

*This switch isn’t mandatory but is required if you wish to email the log file.

Server-Status@contoso.com
-smtp No* SMTP server address to use for the email functionality.

*This switch isn’t mandatory but is required if you wish to email the log file.

mail01.contoso.com

OR

smtp.live.com

OR

smtp.office365.com

-user No* The username of the account to use for SMTP authentication.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

example@contoso.com
-pwd No* The location of the file containing the encrypted password of the account to use for SMTP authentication.

*This switch isn’t mandatory but may be required depending on your SMTP server.

c:\scripts\ps-script-pwd.txt
-usessl No* Add this option if you wish to use SSL with the configured SMTP server.

Tip: If you wish to send email to outlook.com or office365.com you will need this.

*This switch isn’t mandatory but may be required depending on the configuration of the SMTP server.

N/A
-compat No Set this switch if you are using Exchange 2010. Do not set this if you are on Exchange 2013 or 2016. N/A

Change Log

16/10/2017 1.6

  • Changed SMTP authentication to require an encrypted password file.
  • Added instructions on how to generate an encrypted password file.

07/10/2017 1.5

  • Added necessary information to add the script to the PowerShell Gallery.

27/09/2017 1.4

  • Added improved, cleaned logging. Log output is no longer handled by PowerShell’s Transcript functionality.
  • Cleaned up code formatting.

22/07/2017 1.3

  • Improved commenting on the code for documentation purposes.
  • Added authentication and SSL options for e-mail notification.

The Complete Script


<#PSScriptInfo .VERSION 1.6 .GUID 2905a44a-0932-41e9-9d09-b6339a9f0143 .AUTHOR Mike Galvin twitter.com/digressive .COMPANYNAME .COPYRIGHT (C) Mike Galvin. All rights reserved. .TAGS Exchange Mailbox Active Directory Syncronization .LICENSEURI .PROJECTURI https://gal.vin/2017/06/07/powershell-create-mailboxes .ICONURI .EXTERNALMODULEDEPENDENCIES Exchnage Management PowerShell module. Active Directory Management PowerShell module. .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES #>

<# .SYNOPSIS Create Exchange mailboxes for users with no mailbox contained within an OU tree. .DESCRIPTION Create Exchange mailboxes for users with no mailbox contained within an OU tree. This script will: Create mailboxes for users contained witin an OU tree. You can configure the database and retention policy to use. Output and e-mail a log file. This script is designed to be run locally on an Exchange Server. Please note: to send a log file using ssl and an SMTP password you must generate an encrypted password file. The password file is unique to both the user and machine. The command is as follows: $creds = Get-Credential $creds.Password | ConvertFrom-SecureString | Set-Content c:\foo\ps-script-pwd.txt .PARAMETER Ou The AD Organisational Unit (including child OUs) that contains the users to create Exchange Mailboxes for. .PARAMETER Datab The Exchange database to create the mailboxes in. .PARAMETER Rp The retention policy that should be applied to the users. .PARAMETER Compat Use this switch if you are using Exchange 2010. .PARAMETER L The path to output the log file to. The file name will be "Create-Mailboxes.log" .PARAMETER SendTo The e-mail address the log should be sent to. .PARAMETER From The from address the log should be sent from. .PARAMETER Smtp The DNS name or IP address of the SMTP server. .PARAMETER User The user account to connect to the SMTP server. .PARAMETER Pwd The password for the user account. .PARAMETER UseSsl Connect to the SMTP server using SSL. .EXAMPLE Create-Mailboxes.ps1 -Ou "OU=NewUsers,OU=Dept,DC=contoso,DC=com" -Datab "Mail DB 2" -Rp "1-Month-Deleted-Items" -L E:\scripts -Sendto me@contoso.com -From Exch01@contoso.com -Smtp smtp.live.com -User Exch01@contoso.com -Pwd P@ssw0rd -UseSsl This will create mailboxes for users that do not already have one in the OU NewUsers and all child OUs. It will create the mailbox using Mail DB 2 and apply the retention policy "1-Month-Deleted-Items". A log will be output to E:\scripts and e-mail using a secure connection. #>

[CmdletBinding()]
Param(
    [parameter(Mandatory=$True)]
    [alias("Ou")]
    $OrganisationalUnit,
    [parameter(Mandatory=$True)]
    [alias("Datab")]
    $Database,
    [alias("Rp")]
    $Retention,
    [alias("L")]
    $LogPath,
    [alias("SendTo")]
    $MailTo,
    [alias("From")]
    $MailFrom,
    [alias("Smtp")]
    $SmtpServer,
    [alias("User")]
    $SmtpUser,
    [alias("Pwd")]
    $SmtpPwd,
    [switch]$UseSsl,
    [switch]$Compat)

## Count number of users in ou specified without a mailbox
$UsersNo = Get-ADUser -SearchBase $OrganisationalUnit -Filter * -Properties mail | Where-Object {$_.mail -eq $null} | Measure-Object

## If users exist without mailboxes run the script
If ($UsersNo.count -ne 0)
{

    ## If logging is configured, start log
    If ($LogPath)
    {
        $LogFile = "Create-Mailboxes.log"
        $Log = "$LogPath\$LogFile"

        ## If the log file already exists, clear it
        $LogT = Test-Path -Path $Log
        If ($LogT)
        {
            Clear-Content -Path $Log
        }

        Add-Content -Path $Log -Value "****************************************"
        Add-Content -Path $Log -Value "$(Get-Date -Format G) Log started"
        Add-Content -Path $Log -Value ""
    }

    ## If compat is configured load the old Exchange PS Module, if not load the current one.
    If ($Compat)
    {
        Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

        ## Logging
        If ($LogPath)
        {
            Add-Content -Path $Log -Value "$(Get-Date -Format G) Loaded PSSnapin for Exchange 2010"
        }
    }

    Else
    {
        Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn

        ## Logging
        If ($LogPath)
        {
            Add-Content -Path $Log -Value "$(Get-Date -Format G) Loaded PSSnapin for Exchange 2013/16"
        }
    }

    ## Find the users in the OU specified
    $Users = Get-ADUser -SearchBase $OrganisationalUnit -Filter *

    ## For each user that does not have a mailbox, create one and set the retention policy if it has been specified
    ForEach ($User in $Users)
    {
        If ($(Get-ADUser $User -Properties mail).mail -eq $null)
        {
            Enable-Mailbox -Identity $User.SamAccountName -Database $Database -RetentionPolicy $Retention

            ## Logging
            If ($LogPath)
            {
                Add-Content -Path $Log -Value "$(Get-Date -Format G) Creating mailbox for User: $($User.SamAccountName) in Database: $Database with Retention Policy: $Retention"
            }
        }
    }

    ## If log was configured stop the log
    If ($LogPath)
    {
        Add-Content -Path $Log -Value ""
        Add-Content -Path $Log -Value "$(Get-Date -Format G) Log finished"
        Add-Content -Path $Log -Value "****************************************"

        ## If email was configured, set the variables for the email subject and body
        If ($SmtpServer)
        {
            $MailSubject = "Create Mailboxes Log"
            $MailBody = Get-Content -Path $Log | Out-String

            ## If an email password was configured, create a variable with the username and password
            If ($SmtpPwd)
            {
                $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString
                $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt)

                ## If ssl was configured, send the email with ssl
                If ($UseSsl)
                {
                    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $SmtpCreds
                }

                ## If ssl wasn't configured, send the email without ssl
                Else
                {
                    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Credential $SmtpCreds
                }
            }

            ## If an email username and password were not configured, send the email without authentication
            Else
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer
            }
        }
    }
}

## End

If you’d like to get in touch with me, please leave a comment or tweet me.

-Mike

Follow Mike on Twitter: @Digressive

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s