Managing AD User Accounts with PowerShell

Use free AD cmdlets to find, report on, create, and modify user accounts

Dmitry Sotnikov

August 26, 2008

9 Min Read
ITPro Today logo

Active Directory (AD) is a vital part of the Windows enterprise infrastructure.Although Windows PowerShell scripting is available for Windows Server,PowerShell doesn’t include AD cmdlets. To address this need, you can downloada free set of AD cmdlets (www.quest.com/
activeroles-server/arms.aspx)that let you easily perform basic user account operations. These cmdlets hidethe complexities associated with usingActive Directory Service Interfaces (ADSI). You can usethe cmdlets with Active Directory Domain Services (ADDS) or Active Directory Lightweight Domain Services(AD LDS).

You can install the AD cmdlets on any computerrunning PowerShell. They can be used remotely withany AD domain controller (DC) in a network.

When you install the cmdlets, the ActiveRoles ManagementShell for Active Directory shortcut is added to yourStart menu. Clicking this shortcut starts a shell in whichyou can run the AD cmdlets as well as PowerShell’s defaultset of cmdlets. From this shell, you can easily perform suchtasks as finding a user account, finding and reporting ongroups of user accounts, modifying user properties, modifyinguser accounts, and creating user accounts.

Finding a User Account


Finding a user account isn’t easy in VBScript code. Whenyou don’t know the user’s distinguished name (DN), youneed to construct an LDAP query, which can take manylines of code. Not only are VBScript scripts for managingAD long, they require knowledge of LDAP queries, ADschema naming, and other technical details.

Finding a user is much easier with PowerShell.
If youwant to use a logon name to find a user account, all youhave to do is use the Get-QADUser cmdlet. For example,if you want to find the user account associated with thesAMAccountName dsotnikov, you’d type

Get-QADUser dsotnikov

Let’s look at what this cmdlet is doing. First, it establishesa connection with the current AD domain using the account under which you started the shell.If you want to connect to another domain,you can use the Get-QADUser cmdlet's-Service parameter or precede the statementwith the Connect-QADService cmdlet.If you want to make the connection underdifferent credentials, you can use the Get-QADUser cmdlet’s -Credential parameter orits -ConnectionAccount and -ConnectionPassword parameters.

Because only the username is specified(dsotnikov), the Get-QADUser cmdletassumes you want to use its default-Identity parameter to locate the account.(Specifying the name of the default parameteris optional in the AD and Power-Shell cmdlets.) The AD cmdlets providea variety of ways to identify objects.Besides specifying a sAMAccountName(or domainsAMAccountName), you canspecify a display name, DN, user principalname (UPN), SID, or globally unique identifier(GUID), as in

Get-QADUser 'Dmitry Sotnikov'Get-QADUser  'cn=dsotnikov,ou=users,dc=quest,  dc=com'Get-QADUser [email protected] S-123-4567…Get-QADUser  ABCD-1234-5677-98FE-CD43

(Column widths force us to wrap code. So,although the second command appears ontwo lines here, you would enter it on oneline in the shell. The same holds true for theother multiline commands in this article.)Note that you need to enclose the parameterin quotes if it contains spaces (like in thedisplay name example) or commas (like inthe DN example). This is done to help thePowerShell parser understand that you’repassing in a single string.

Finding and Reporting on Groups ofUser Accounts


Systems administrators often need to findand report on groups of user accounts. TheGet-QADUser cmdlet also handles this task.For example, if you want to see all the usersin the accounting department, you’d use the-Department parameter, as in

Get-QADUser -Department Accounting

If you want to see all the users in the Londonoffice, you’d use the -City parameter,like this

Get-QADUser -City London

As these examples show, you can use thedisplay names of the user attributes (e.g.,Department, City), so knowing the attributes’LDAP names is no longer required.However, you can use the LDAP names ifyou already know them. For example, if youwant to use the LDAP name for the Cityattribute, you can run

Get-QADUser -L London

As Table 1 shows, Get-QADUser has manyattribute-specific parameters you can usein searches. Plus, there are many otheravailable parameters, such as -Identity,-Credential, -ConnectionAccount, and -ConnectionPassword. To get the fullparameter list, type

Get-Help Get-QADUser -Full

Getting the information retrieved by Get-QADUser into a table, list, or .html file foreasy viewing is simple. All you need to do istell PowerShell how to format the results.

In both PowerShell and ActiveRolesManagement Shell for Active Directory, theGet- cmdlets produce a collection of objects.To change the way in which these objectsare presented, you need to direct, or pipe(|), the collection to another cmdlet. Forexample, if you want to present the informationabout the London users in a table, you’dpipe Get-QADUser’s results to PowerShell’sFormat-Table cmdlet. To specify what attributesyou want in the table and the order inwhich they appear, you use Format-Table’s-Property parameter. The -Property parameteris the default parameter, so specifying itin the command is optional. Thus, to presentthe London data in a table that includesthe users’ names, departments, and titles,you’d type

Get-QADUser -City London |  Format-Table Name,Department,Title

If you’d rather have the London data in alist, you can use PowerShell’s Format-Listcmdlet, as in

Get-QADUser -City London |  Format-List Name,Department,Title

For more information about how to use theFormat-Table and Format-List cmdlets andwhat the results look like, see “PowerShell101, Lesson 2,” March 2008, InstantDoc ID97959.

If you want to convert and save theLondon data in an .html file, you can usePowerShell’s ConvertTo-HTML and Out-File cmdlets in the command

Get-QADUser -City London |  ConvertTo-HTML  -Property Name,Department,Title  -Title 'London Staff' |  Out-File C:LondonUsers.html

Continue on Page 2

ConvertTo-HTML selects the propertiesspecified with the -Property parameter (i.e.,Name, Department, and Title), adds thetitle specified with -Title property (i.e., LondonStaff), and produces the correspondingHTML code. After the selected data isconverted into HTML, it’s saved in the C: LondonUsers.html file with the Out-Filecmdlet. For more information about theConvertTo-HTML and Out-File cmdlets, seethe PowerShell documentation.

Modifying User Properties


To modify user properties, you use the Set-QADUser cmdlet. You can use many of theattribute-specific attributes for Set-QADUserthat you use for Get-QADUser (see Table 1).For example, to set Paris as the office locationfor a user, you’d use a command such as

Set-QADUser 'Dmitry Sotnikov'  -City Paris

Bulk changes are just as easy. You can relocateeveryone from the London office to theParis office with the command

Get-QADUser -City London |  Set-QADUser -City Paris

To reset a password, you use Set-QADUser’s-UserPassword parameter in a commandsuch as

Set-QADUser 'Dmitry Sotnikov'  -UserPassword '!@#Quh*$%'

Modifying User Accounts


There’s more to managing user accountsthan just reporting on and setting theirproperties. Other common tasks includeenabling, unlocking, moving, and deletinguser accounts. To enable user accounts,you use the Enable-QADUser cmdlet. Forexample, the command

Get-QADUser -Disabled |  Enable-QADUser

first uses Get-QADUser’s -Disabled parameterto find all the disabled accounts, after which ituses Enable-QADUser to enable them.

To unlock accounts, you use the Unlock-QADUser cmdlet. For example, the command

Get-QADUser -Locked -Title Manager |  Unlock-QADUser

first uses Get-QADUser’s -Locked and-Title parameters to find the locked outaccounts of users whose title is manager,then uses Unlock-QADUser to unlock thoseaccounts.

To move user accounts, you use theMove-QADObject (and not Move-QADUser)cmdlet. Move-QADObject is a generic cmdletthat you can use to move any AD object toa different container. For example, to reorganizeuser accounts into organizational units(OUs) based on geography, you might use acommand such as

Get-QADUser -City 'New York' |  Move-QADObject NewParentContainer  quest.com/staff/NewYork

This command begins by finding all theusers in the New York office, then pipesthe results to Move-QADObject, whichmoves them to the specified container.Note that the canonical name (quest.com/staff/NewYork) is used to specify the targetcontainer. You could use a DN (e.g., cn=NewYork,ou=staff,dc=quest,dc=com)instead, but canonical names are muchshorter and easier to type.

To delete user accounts, you use Remove-QADObject, a generic cmdlet that lets youdelete any AD object. You simply specify theobject to delete, as in

Remove-QADObject 'Unlucky One'

Although you’ll be given a warning messagealong with a prompt to confirm the deleteaction, it’s highly recommended that youuse PowerShell’s -WhatIf parameter withRemove-QADObject first. When you usethis parameter, PowerShell lists what objectswill be deleted but doesn’t actually deletethem. This is especially handy when you usepipelines for input and you’re not certainwhich accounts might get into the result set.For example, suppose you want to use Get-QADUser to retrieve any disabled accountswhose name starts with the letter a in thequest.com/recycled container and pipe the retrievedobjects to Remove-QADObject fordeletion. By using the -WhatIf parameter inthe command

Get-QADUser -Name a* -Disabled  -SearchRoot quest.com/recycled |  Remove-QADObject -WhatIf

you’ll know exactly which objects will bedeleted. Note that QADUser’s -SearchRootparameter limits the scope to the specifiedcontainer.

Continue on Page 3

Creating User Accounts


Many systems administrators would probablylike an effortless way to create useraccounts for newly hired employees. Afterall, who wants to repeatedly perform thisroutine task each time HR hires a newemployee? To automate this task, you canuse the New-QADUser cmdlet. For example,the command

New-QADUser -Name dsotnikov  -ParentContainer quest.com/users  -UserPassword 'P@ssw0rd'

creates a new user account nameddsotnikov in the quest.com/users container.Although -Name and -ParentContainer arethe only two mandatory parameters forthe New-QADUser cmdlet, the accountwill be created disabled unless you alsospecify a password with New-QADUser’s-UserPassword parameter. Alternatively, youcan set a password later by using the Set-QADUser cmdlet and enable the accountwith the Enable-QADUser cmdlet.

If you want to create a user account thathas more attributes set, you can specify themin a New-QADUser command such as

New-QADUser -Name 'Dmitry Sotnikov'  -ParentContainer quest.com/users  -DisplayName 'Dmitry Sotnikov'  -UserPassword 'P@ssw0rd'  -sAMAccountName dsotnikov  -FirstName Dmitry  -LastName Sotnikov |  Set-QADUser  -UserMustChangePassword $true

At the end of this command, notehow the new user object is pipedto the Set-QADUser cmdlet and its-UserMustChangePassword parameter isset to $true ($true and $false are the Power-Shell way of expressing the correspondingBoolean values). This part of the command makes sure that the user is asked to reset thepassword at the first logon.

Now, typing all that information isn’texactly quick and painless, especially if youneed to create many user accounts. Fortunately,PowerShell comes with commaseparatedvalue (CSV) file support. TheImport-CSV cmdlet opens a CSV file andassumes the first row in the file has thenames of the object properties that are listedin subsequent rows.

If the CSV file’s column names coincidewith the names of the New-QADUser parameters,like in the following sample file

Name,sAMAccountName,UserPasswordFirst User,FUser,P@ssw0rdSecond User,SUser,P@ssword

you can simply pipe the CSV file’s contentsto New-QADUser. You just need to use the

Import parameter, as in  Import-CSV 'C:provision.csv' |  New-QADUser -Import  -ParentContainer quest.com/users  -City Columbus

As this example shows, you can add otherparameters (in this case, -ParentContainerand -City) to the New-QADUser cmdlet.

With this setup, you can tell HR to putthe information about new employees in aCSV file in an agreed-on location and youcan schedule a command like the one justgiven to run daily. Because you won’t haveto manually create those accounts anymore,you’ll have more time for other administrativetasks.

If you want to try the New-QADUsercmdlet in a test environment, you can usethe command

1..500 | ForEach-Object {  New-QADUser  -ParentContainer quest.test/test  -Name "testuser$_"  -SamAccountName "testuser$_"  -UserPrincipalName  "[email protected]"  -FirstName "testUser$_"  -LastName "example$_"  -UserPassword "P@ssword@_$_"}

to quickly create 500 test user accounts withunique attributes. This code uses Power-Shell’s range operator (..) to get a collectionof 500 numbers (1 through 500). The collection is piped to the ForEach-Object cmdlet,which cycles though the collection, puttingeach number inside the various parameters’string values so that, for example, testuser$_becomes testuser1 in the first loop, testuser2in the second loop, testuser3 in the third loop, and so on. Note the use of the doublequotes around the string values. The doublequotes tell PowerShell to automaticallyevaluate the $_ variable inside the strings.(If you’re unfamiliar with the $_ variable, see“PowerShell 101, Lesson 2.") Using singlequotes won’t work.

Easily Manage User Accountsand a Lot More


As you can see, ActiveRoles ManagementShell for Active Directory contains manycmdlets that you can use to manage useraccounts. It also contains many more cmdlets.Version 1.1 has 40 cmdlets for managingnot only users but also groups, group memberships,computers, permissions, WindowsServer 2008 fine-grained password policies,and more. To see the full list of cmdletsand what they do, you can download the“ActiveRoles Management Shell for ActiveDirectory - Administrator’s Guide” from www.quest.com/powershell/activerolesserver.aspx or visit the online referenceat wiki.powergui.org/index.php/QAD_cmdlets_reference.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like