Automating Active Directory tasks with PowerShell

PowerShell is a powerful tool that administrators can use for automating many different kinds of tasks in a Windows environment. One area where PowerShell’s capabilities can be particularly helpful is in performing certain common Active Directory administration tasks like automating the creation of new users in your AD environment. For those who are still relatively new to PowerShell, my colleague Adam Bertram, who is a well-known guru in the PowerShell community, demonstrates simply below how you can easily do this by using some simple PowerShell scripting techniques you can try out and then customize as needed. Adam is a 20-year veteran of IT and an experienced online business professional who has worked as an entrepreneur, IT influencer, Microsoft MVP, blogger, trainer, author and content marketing writer for multiple technology companies. Adam is also the founder of the popular IT career development platform TechSnips and frequently posts articles on his site, and you can connect with him on LinkedIn or follow him on Twitter at @adbertram. Let’s turn the floor over to Adam

Automating Active Directory jobs with PowerShell scripts

PowerShell seems to have the ability to automate just about anything. Active Directory is no different. By downloading a freely available PowerShell module, an IT admin can manage every facet of AD and build powerful scripts to save time with all kinds of tasks. The best part is that knowledge of LDAP, ADSI and other typically developer-focused terms is not necessary. The PowerShell cmdlets take care of that stuff for you.

To get started, we’re going to assume you’re on a computer that is joined to an Active Directory domain and that you have the appropriate rights. I’ll be performing a few demos with an account that’s a member of Domain Admins, but your account doesn’t have to be. I suggest running these scripts, seeing what works and tweaking your rights from there.

Installing the Active Directory module

The first task you’ll need to do is grab the ActiveDirectory PowerShell module. Unlike other modules that are available by just running Install-Module, the ActiveDirectory module is only available as a component of the Remote Server Administration Tools (RSAT). If you’re on a recent version of Windows 10, you can also now run Add-WindowsCapability -online -Name "Rsat.ActiveDirectory.DS-LDS.Tools~~~~".

Once you’ve got RSAT downloaded and have opened up your PowerShell console, you should have all of its cmdlets available to you. You can verify this by running Get-Command.

PS> Get-Command -Module ActiveDirectory

CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Add-ADCentralAccessPolicyMember ActiveDirectory
Cmdlet Add-ADComputerServiceAccount ActiveDirectory
Cmdlet Add-ADDomainControllerPasswordReplicationPolicy ActiveDirectory
Cmdlet Add-ADFineGrainedPasswordPolicySubject ActiveDirectory
Cmdlet Add-ADGroupMember ActiveDirectory
Cmdlet Add-ADPrincipalGroupMembership ActiveDirectory

If you see a bunch of *-AD commands show up, you’re in business! If not, something has gone haywire with the RSAT install.

Finding users

Once you’ve got the ActiveDirectory module downloaded, you can begin to explore. I always try to look at the Get cmdlets first because I know those won’t modify anything. They are usually the safest. A common task IT admins must perform is managing users. Looking down through the list of commands available, you’ll see a Get-AdUser command. This command only requires a single parameter called Filter. If running this command on a domain-joined machine, PowerShell should automatically find the domain controller to query.

By using an asterisk, I can pull all users from AD. This can take a bit if you’ve got lots of users and isn’t recommended. Instead, you should provide some criteria to the filter parameter. The criteria of the Filter parameter can be complex, but you’ve always got this resource from Microsoft if you need it. This time, let’s say I just want to find all of the users with the last name of Bertram. By providing the expected criteria to the Filter parameter, it will only return those accounts I want to see.

PS> Get-ADUser -Filter "surName -eq ‘Bertram’"

DistinguishedName : CN=Anne Bertram,OU=Marketing,DC=mylab,DC=local
Enabled : False
GivenName : Anne
Name : Anne Bertram
ObjectClass : user
ObjectGUID : b98fd0c4-3d5d-4239-8245-b04145d6a0db
SamAccountName : abertram
SID : S-1-5-21-4117810001-3432493942-696130396-3142
Surname : Bertram
UserPrincipalName : abertram@mylab.local

I can also pull individual accounts by using the samAccountName with the Identity parameter as well.

Get-ADUser -Identity ‘abertram’

Creating users

We can also create new users as well with the New-AdUser cmdlet. This cmdlet has parameters for just about every AD attribute you’d need to set for a user. Below I’m creating a user by the name of David Jones with a username of djones and a password of p@$$w0rd10. David will have to change his password when he first logs on. Notice that I couldn’t directly pass the password to the command. Instead, I had to convert it to a secure string. Some attributes will force you to modify them a bit before they can be set.

$NewUserParameters = @{
‘GivenName’ = ‘David’
‘Surname’ = ‘Jones’
‘Name’ = ‘djones’
‘AccountPassword’ = (ConvertTo-SecureString ‘p@$$w0rd10’ -AsPlainText -Force)
‘ChangePasswordAtLogon’ = $true
New-AdUser @NewUserParameters

Adding users to groups

Another command task when managing AD is adding users to groups. Along with being able to create groups themselves with the New-AdGroup command, we can use the Add-AdGroupMember command to add an existing user to any group. In this example, I’m adding the AD account with the samAccountName of djones to the Account department. You’ll find that the Identity parameter is shared across lots of the AD cmdlets.

Add-AdGroupMember -Identity ‘Accounting’ -Members ‘djones’

Automating user creation

Now that we’ve got the basics out of the way let’s see how we can apply this knowledge and build a script. Here I’m reading a CSV file row by row and passing each row’s attributes to the New-AdUser command. This prevents me from having to type out the New-AdUser command over and over again if I’ve got a lot of users to create at once.

In the example below, the CSV file contains three columns; FirstName, LastName, and UserName. PowerShell is reading each value for these fields, assigning their values as parameter values and then passing those parameters to the New-AdUser command.

Import-Csv -Path ‘C:\Employees.csv’ | foreach {
$NewUserParameters = @{
‘GivenName’ = $_.FirstName
‘Surname’ = $_.LastName
‘Name’ = $_.UserName
‘AccountPassword’ = (ConvertTo-SecureString ‘p@$$w0rd10’ -AsPlainText -Force)
New-AdUser @NewUserParameters

If you can learn how to manage one type of AD object at a time, you can eventually create all kinds of automation. Users are just one kind of AD object. Browse around the AD cmdlets available. You’ll see that the Active Directory module provides support for just about every AD object out there! The options for automating Active Directory task are endless.

If you’d like to learn more about Active Directory and PowerShell, be sure to check out I’ve written dozens of posts on automating Active Directory with PowerShell along with a ton of other PowerShell content.

Featured image: Shutterstock

Mitch Tulloch

Mitch Tulloch is Senior Editor of both WServerNews and FitITproNews and is a widely recognized expert on Windows Server and cloud technologies. He has written more than a thousand articles and has authored or been series editor for over 50 books for Microsoft Press and other publishers. Mitch has also been a twelve-time recipient of the Microsoft Most Valuable Professional (MVP) award in the technical category of Cloud and Datacenter Management. He currently runs an IT content development business in Winnipeg, Canada.

Published by
Mitch Tulloch

Recent Posts

Deploy Windows from the cloud to on-premises hardware? Yes, you can

Wouldn’t it be nice if you could deploy Windows from the cloud while sipping an…

3 days ago

Blackbaud data breach after ransomware attack hits universities, nonprofits

Blackbaud, a cloud services provider focused on the education sector and nonprofits, suffered a data…

3 days ago

Sending email from Linux terminal: Efficient and powerful solution

Knowing how to send email from the Linux command line is important, especially when you…

4 days ago

Family Tree Maker genealogy software experiences data breach

A data breach affecting popular genealogy software Family Tree Maker has been discovered and patched,…

4 days ago

Review: Microsoft 365 monitoring solution GSX Gizmo

In a world of distributed employees, GSX Gizmo provides monitoring of Microsoft 365 and on-premises…

4 days ago

Nmap: All about this free open-source network monitoring tool

Nmap is a free open-source tool used to scan networks, identify vulnerabilities, find open ports,…

5 days ago