PowerShell: Create Active Directory Users From CSV File

For years I’ve had a AD user import VBS script as part of my toolkit, I thought it was about time to update it to PowerShell as well as add a few new features.

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

Compatibility and Requirements

This script has been tested running on Windows Server 2016 and Windows Server 2012 R2 Domain Controller and on a Windows 10 client. It requires the Active Directory PowerShell module be installed.

The -file Parameter

As with my other scripts, it can optionally generate a log and email the log if configured to do so, and I’ve implemented options via command line switches. When running the script via Schedule Tasks or the command prompt be sure to use the -file parameter before specifying the script, so you can use “double quotes” for the command line switches that need them, if you do not use -file, then you should use ‘single quotes’.

CSV File Formatting

The first line of the CSV file should be the field names so the script (and you) knows what each field is for.

The CSV file should be laid out like so: Firstname,Lastname,SAM,Password

The Complete Script

# -------------------------------------------
# Script: Create-Accounts-CSV_v1-2.ps1
# Version: 1.2
# Author: Mike Galvin twitter.com/digressive
# Date: 22/07/2017
# -------------------------------------------

Param(
    [parameter(Mandatory=$true)]
    [alias("csv")]
    $userslist,
    [parameter(Mandatory=$true)]
    [alias("ou")]
    $organisationalunit,
    [parameter(Mandatory=$true)]
    [alias("upn")]
    $adupn,
    [alias("homeletter")]
    $homedrive,
    [alias("homepath")]
    $homeunc,
    [alias("group")]
    $adgroup,
    [alias("expire")]
    $adexpire,
    [alias("l")]
    $logpath,
    [alias("sendto")]
    $mailto,
    [alias("from")]
    $mailfrom,
    [alias("smtp")]
    $smtpserver,
    [alias("user")]
    $smtpuser,
    [alias("pwd")]
    $smtppwd,
    [switch]$usessl)

## If users list csv file exists then run the script
If (Test-Path $userslist) {

    ## Start Log
    If ($logpath) {
        $logfile = "AD-Account-Creation.log"
        $log = "$logpath\$logfile"
        Start-Transcript $log
    }

    ## Set variable for the foreach loop
    $usercsv = Import-Csv -Path "$userslist"

    ## Set variables based on the data in the columns of the csv file
    ForEach ($user in $usercsv) {
        $displayname = $user.Firstname + " " + $user.Lastname
        $userfirstname = $user.Firstname
        $userlastname = $user.Lastname
        $sam = $user.SAM
        $upn = $sam + "@$adupn"
        $description = $displayname
        $password = $user.Password

        ## Create new AD user from each line of the csv file
        New-ADUser -Name $sam -DisplayName "$displayname" -SamAccountName $sam -UserPrincipalName $upn -GivenName "$userfirstname" -Surname "$userlastname" -Description "$description" -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Enabled $true -Path "$organisationalunit" -ChangePasswordAtLogon $true –PasswordNeverExpires $false -AccountExpirationDate $adexpire -Verbose
        
        ## If the home drive option is configured, set the home drive for each user
        If ($homedrive) {
            Set-ADUser $sam -HomeDirectory $homeunc\$sam -HomeDrive $homedrive -Verbose
        }

        ## If the AD group option is configured add the user to the group
        If ($adgroup) {
            Add-ADGroupMember "$adgroup" $sam -Verbose
        }
    }

    ## If log was configured stop the log
    If ($logpath) {
        Stop-Transcript

        ## If email was configured, set the variables for the email subject and body
        If ($smtpserver) {
            $mailsubject = "AD Account Creation Log"
            $mailbody = Get-Content -Path $log | Out-String

            ## If an email password was configured, create a variable with the username and password
            If ($smtppwd) {
                $smtpcreds = New-Object System.Management.Automation.PSCredential -ArgumentList $smtpuser, $($smtppwd | ConvertTo-SecureString -AsPlainText -Force)

                ## 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

Command Line Options

Here are the command line options available to you, with some examples of how to use them.

Command Line Switch Mandatory Description Example
-csv Yes Location and name of the csv file containing the user accounts to be created. E:\scripts\new-users.csv
-ou Yes Enter the DN (Distinguished Name) of the OU that you wish to put the new users in. The DN must be surrounded by “double quotes.” “ou=Imported_Accounts,dc=contoso,dc=com”
-upn Yes Enter the string you wish to use for the users UPN. contoso.com
-homeletter No* Enter the drive letter to use for the Home Drive. *This setting must be set along with the -homepath. H:
-homepath No* Enter the unc path to use for the location of the home drive. The users folder will be created automatically. *This setting must be set along with the -homeletter. \\filesrv01\share
-group No Enter the DN (Distinguished Name) of a group that the users should be added to, if required. “cn=Marketing,ou=UserGroups,dc=contoso,dc=com”
-expire No Enter the date the accounts should expire if required. The date format should be the same as the local systems format. 31/12/2018
-l No Location to store the optional log file. The name of the log file is automatically generated. E:\scripts\log
-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 password of the account to use for SMTP authentication.

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

P@ssw0rd
-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

Change Log

22/07/2017 1.2

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

As always I hope this helps in some way. If you’d like to get in touch with me please leave a comment or tweet me.

-Mike

Follow Mike on Twitter: @Digressive

3 thoughts on “PowerShell: Create Active Directory Users From CSV File

  1. Good Job with the Script!
    But it dont want to work for me, maybe because of the Windowsupdate last Weekend.
    Trying to get it to work with Windows Server 2012r2 but geting this error every time:

    AUSFÜHRLICH: Ausführen des Vorgangs “New” für das Ziel “CN=srogers0203,Teilnehmer”.
    New-ADUser : Die Syntax des Objektnamens ist ungültig
    In C:\Users\Administrator\Desktop\Unbenannt2.ps1:64 Zeichen:9
    + New-ADUser -Name $sam -DisplayName “$displayname” -SamAccountName $sam – …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (CN=srogers0203,Teilnehmer:String) [New-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser

    Like

    • Hi Georg, I’ll try to help. I don’t think it’s due to a Windows Update, as I last tested it on the weekend. I could do with a bit more information but based on what you’ve posted it looks like that the script is stopping at the point where it creates the user. Does the CSV file have any extra characters that might be stopping it from completing, or perhaps the CSV file doesn’t have the correct formatting. The CSV file should be laid out like this: Firstname,Lastname,SAM,Password.

      Hope that helps, but let me know more information if you can.

      Like

  2. Pingback: PowerShell: Create Active Directory Users From CSV File — Stick To The Script! – Computer Services

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