Creating Users Easily with PowerShell


As most people know, I like to make my life easy at work. That doesn’t mean I’m afraid of work, I just like to automate or simplify it where I can. I like to use PowerShell for this.

Another reason besides the convenience or lack of time why you should solve tasks through scripts is a consistent level of quality. Let’s face it, who doesn’t know this, even if there are checklists, you might forget one step when you get distracted.

7e4248e465774f129d88e68e5040ddd4 Creating Users Easily with PowerShell 1

I always recommend automating simple things as much as possible so that the admins have time for the important stuff. Today I’d like to go through a few examples on how to create users. Since the requirements of this process are very individual, it can serve only as examples or building blocks for its own development. To make it a bit easier to use as an idea donor, I’ll show you single building blocks and finally the whole script I use in my test environment.

Note about program and Power Shell Code

The code contained here serves as an example. I do not assume any warranty, guarantee or support for the code or its components. Use the code at your own risk.

I always recommend to have a close look at the scripts before using them.

Connection to Active Directory

The first step is the connection to the Active Directory, which we load for the required module. Here I like to check if it has already been loaded. What I also like to do is to specify a domain controller for all commands. This makes sense so that I don’t have to wait for replication, because every time I might end up on a different server. Since I don’t always want to specify one, or want to hardwire the DC, I let the script select one if I don’t specify one for the script.

if(@(get-module | where-object {$_.Name -eq "ActiveDirectory"} ).count -eq 0) {import-module ActiveDirectory}
IF ($DC -eq "") { $DC = $(Get-ADDomainController).HostName ; Write-Verbose "no DC defined, use $DC"  }

Creating the user

There are many options you can set when creating a user. A list of all options can be found in the documentation of the PowerShell commands New-ADUser and Set-ADUser. I like to go into my scripts and just set the additional options with New-ADUser that are the same for all users. The rest I modify with Set-ADUser. It is easier to work with parameter switches and IF queries when programming the PowerShell script than to build different strings together for the “Ultimate” New-ADUser command.

When selecting the possible options, you have to consider which options do I need in the organization? Besides the classic information attributes like address, phone number and Co. there are some AD attributes, which I mostly implement, here some examples:

  • Password change at first login (ChangePasswordAtLogon)
  • Enabled
  • departmental or group membership
  • Expiration date (AccountExpirationDate), for example, for temporary employees and interns
  • manager

If you work with the switch parameter in the PowerShell script, this can be done very easily

New-ADUser -Name $Username -GivenName $Vorname -Surname $Nachname -Path $OU -AccountPassword $SecPass -DisplayName $($Vorname+" "+$Nachname) -EmailAddress $Email -UserPrincipalName $UPN -OtherAttributes @{proxyAddresses=$("SMPT:"+$Email)} -Server $DC
Start-Sleep -Seconds 10
IF ( $PWwechsel ) { Set-ADUser -Identity $Username -ChangePasswordAtLogon $true -Server $DC } ELSE { Set-ADUser -Identity $Username -ChangePasswordAtLogon $false -Server $DC } 
IF ( $Aktiviert ) { Set-ADUser -Identity $Username -Enabled $true -Server $DC ; Write-Verbose "Activate$Username" }
IF ( $Abt -eq "" ) { Write-verbose "No department selected" } Else { Add-ADGroupMember -Identity $Abt -Members $Username }

Adding licenses for Office 365

Many companies today use Microsoft Office 365, there are PowerShell commands for this too, why not use them? For this example, I’m assuming synchronization with Azure AD Connect. For simplicity, this sample script works with a manual administrative login to the Azure AD, for productive use I would consider a service account with RBAC or another form of authentication.

First of all, I need the right toolbox again, the PowerShell modules. Therefore I use the function PowerShellGet to load modules from the PowerShell Galerie to load modules from the PowerShell gallery. This is integrated since PowerShell 5 but can be installed for PowerShell versions 3 and higher.

Also here I check before I load the module if it is available.

Try { Connect-AzureAD } catch { Write-Verbose "Install AzureAD Modul" ; Install-Module -Name AzureAD -Force ; Connect-AzureAD }

In order to assign a license for a new user, the user must be synchronized first. The default time for AAD Connect is every 30 minutes. If you know me, I don’t want to wait for that much. So I inform the AADConnect of my wish for synchronization and check when it is ready. Then I assign the appropriate Office365 or Microsoft365 license to the user.

Write-Verbose "Start AAD Sync"
   Invoke-Command -ComputerName $ADCServer -ScriptBlock { Start-ADSyncSyncCycle -PolicyType Delta }
   while ( $(try {Get-AzureADUser -ObjectId $Email} catch {}).count -lt 1) { start-sleep -Seconds 10 ; Write-Verbose "Wait for user appear online"}
   #Assign License
   Set-AzureADUser -ObjectId $Email -UsageLocation "DE"
   $license = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
   $licenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
   $license.SkuId = (Get-AzureADSubscribedSku | Where-Object -Property SkuPartNumber -Value $O365Lic -EQ).SkuID
   $licenses.AddLicenses = $license
   Set-AzureADUserLicense -ObjectId $Email -AssignedLicenses $licenses
   Write-Verbose "Assigned Licenses: $($(Get-AzureADUserLicenseDetail -ObjectId $Email ).SkuPartNumber)"

The nice kind of say Welcome

I always find it nice to welcome new employees in the name of IT and to give you the most important information directly. This could be information such as the hotline number, the page of the ticket system or the favourite type of sweets in IT (don’t laugh, I know some companies where a kilo of cookies accelerates the process amazingly). I can pack all this information in an email template and send it personalized when I create the user account.

To send emails with the PowerShell I always use the same function module. It also handles authentication and TLS for SMTP if needed.

 Function SendEmailStatus($From, $To, $Subject, $SmtpServer, $BodyAsHtml, $Body)
 {        $SmtpMessage = New-Object System.Net.Mail.MailMessage $From, $To, $Subject, $Body
 $SmtpMessage.IsBodyHTML = $BodyAsHtml
 $SmtpClient = New-Object System.Net.Mail.SmtpClient $SmtpServer 
         IF ($TLS) { $SmtpClient.EnableSsl = $true }
         IF ($SmtpAuth) { $SmtpClient.Credentials = New-Object System.Net.NetworkCredential($smtpuser, $smtppw) }
 If($? -eq $False){Write-Warning "$($Error[0].Exception.Message) | $($Error[0].Exception.GetBaseException().Message)"}
 Remove-Variable SmtpClient
 Remove-Variable SmtpMessage

I can enrich the content of the mail as HTML with variables from the script, for example, “Welcome $firstname”. The call of the email function is accordingly simple:

SendEmailStatus -From $From -To $Email -Subject $WelcomeSub -SmtpServer $SmtpServer -BodyAsHtml $True -Body $WelcomeBody 

Of course, I can also use this function to send the manager a random initial password.


What else can you integrate into such a script?

In principle, I can expand it for anything I need. Here are some possible ideas I’ve come across before:

  • Create a personal VM / VDI
  • Advanced group assignments via PowerShell switch, location information or department assignment
  • Creating a telephone number in the PBX and maintaining the telephone number in the AD
  • Adding a photo to the AD
  • Mail to colleagues about new MA (query via the same manager)
  • Mail to providers of outsourced systems to also create a user there.
  • Mail to the marketing department to provide a set of corporate gifts (mug, pen, etc.) on the first working day.
  • Automatic creation of the mail address based on a fixed convention
  • Check the entries, for example, whether the SAM account name is too long or whether the e-mail also corresponds to the schema.

There are also still possibilities to add more automation. For example, the HR department could be provided with a directory containing a CSV file. Once a night the system script runs, imports the data and creates the users. The script then sends a status mail to HR or IT. For this purpose, the script should be adapted to full automation.

There are no limits to your imagination here.

The User Create Script Sample

This article first appeared on in German.

This article is a translation of the article “Benutzer einfachen anlegen mit PowerShell” (Published – 2019-01-22). Links may refer to other articles, these may also be available in English language.

Also it can be, that I still use screenshots of German systems. However, where it is possible for me with little effort, I insert screenshots of English systems.