PowerShell How-To

Automating Active Directory Jobs with PowerShell Scripts

PowerShell seems to have the ability to automate just about anything. Active Directory (AD) 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 on 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.

If you'd like to learn more about AD and PowerShell, I encourage you check out my Web site, where I've written dozens of posts on automating AD with PowerShell along with a ton of other PowerShell content.

To get started, we're going to assume you're on a computer that's joined to an AD 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~~~~0.0.1.0".

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                    1.0.0.0    ActiveDirectory
Cmdlet          Add-ADComputerServiceAccount                       1.0.0.0    ActiveDirectory
Cmdlet          Add-ADDomainControllerPasswordReplicationPolicy    1.0.0.0    ActiveDirectory
Cmdlet          Add-ADFineGrainedPasswordPolicySubject             1.0.0.0    ActiveDirectory
Cmdlet          Add-ADGroupMember                                  1.0.0.0    ActiveDirectory
Cmdlet          Add-ADPrincipalGroupMembership                     1.0.0.0    ActiveDirectory
<snip>

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 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 it 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 : [email protected]

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 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 ActiveDirectory module provides support for just about every AD object out there. The automation options are endless!

About the Author

Adam Bertram is a 20-year veteran of IT. He's an automation engineer, blogger, consultant, freelance writer, Pluralsight course author and content marketing advisor to multiple technology companies. Adam also founded the popular TechSnips e-learning platform. He mainly focuses on DevOps, system management and automation technologies, as well as various cloud platforms mostly in the Microsoft space. He is a Microsoft Cloud and Datacenter Management MVP who absorbs knowledge from the IT field and explains it in an easy-to-understand fashion. Catch up on Adam's articles at adamtheautomator.com, connect on LinkedIn or follow him on Twitter at @adbertram or the TechSnips Twitter account @techsnips_io.


comments powered by Disqus
Most   Popular