Essential PowerShell Cmdlets for Managing Active Directory

Essential PowerShell Cmdlets for Managing Active Directory
By

Active Directory and PowerShell together offer the system administrator a powerful set of cmdlets to manage and to automate standard domain related tasks. Every company from the smallest proprietorship to the largest enterprise has Windows servers that use Active Directory (AD). Active Directory domains are security domains used for user authentication, for permitting access to network resources, and for tracking various network resources through the integrated domain naming system (DNS) service.

PowerShell's AD module allows you to query AD resources, add, remove, and change resources, and to work with user accounts, policies, and objects.

The setup used for this article is a Windows 7 Enterprise system with PowerShell 4.0 installed and a fully updated and a pair of patched Windows Server 2008 R2 domain controllers running a Windows 2008 R2 domain level. The two domain controllers are VMware virtual machines.

Domain Controllers:     SERVER1, SERVER2                                                          
Domain:     MW.LOCAL
Domain Level:     Windows 2008 R2


Standard PowerShell AD management takes place on a system that's within the domain. That is to say, that if you manage an AD domain, you'll need to do so from a system (workstation or server) that's a member of the domain you want to manage. This is not a strict requirement, however, managing a domain outside of your "home" domain is a bit clumsy and can be confusing. Domain trust relationships make managing "foreign" domains easier. That said, you learn how to connect to "foreign" domains in this article out of necessity to do so in large enterprise environments.

Installing the Active Directory Module for PowerShell

Before attempting to install the Active Directory module, check to see if it's already available to you by entering the following cmdlet:

PS C:\> Get-Module –ListAvailable

    Figure 1: Obtaining a list of available modules.

As you can see, this system already has the AD module available for import. If the AD module isn't listed, then you'll have to install it via Control Panel->Add/Remove Programs->Turn Windows features on or off. The module should be listed under the Remote Server Administration Tools (RSAT) list. Select it, click OK, and allow the installation to proceed.

If you do not find the module listed, you'll have to download the Windows Management Framework 4.0 at microsoft.com, or download the RSAT at here.

After installation and reboot, reopen PowerShell and import the Active Directory module.

PS C:\> Import-Module ActiveDirectory

The only response you'll see from the system is shown in Figure 2 below. This progress indicator shows that you are installing the Active Directory module. Once complete, you now have access to 76 Active Directory cmdlets; 22 are Get cmdlets.
    Figure 2: Loading the Active Directory module into PowerShell.

Exploring Your Active Directory Environment

PowerShell's "Get" cmdlets are a safe bet for exploring your Active Directory setup. The "Get" cmdlets don't change anything in AD, nor do they disrupt any workflows by locking records. These cmdlets are the equivalent of using the SELECT keyword in standard SQL, so don't worry that they induce any significant stress on your AD database or domain controllers. You'll find the complete list of AD cmdlets on Microsoft's Windows Server site at technet.microsoft.com.

The first cmdlet to begin our exploration process is Get-ADDomain. Get-ADDomain provides you with a list of information about your domain that you'll find valuable as you discover your domain and its resources. See Figure 3 below.

PS C:\> Get-ADDomain

    Figure 3: Exploring AD domain information via Get-ADDomain.

As you can see in Figure 3, this simple cmdlet provides a wealth of detail including:

  • Infrastructure Master Server Name (SERVER1)
  • Domain Mode (Windows 2008 R2)
  • Domain SID
  • Domain Name (MW)
  • Domain NETBIOS Name (MW)

Querying AD for the existence of a particular user is a common practice and one that works perfectly at the command line. This query yields useful information about the user, if the user exists in AD.

PS C:\> Get-ADUser khess

     Figure 4: Querying AD for the existence of a user (khess).

If you don’t know the user's account name, you can query the AD database in a more general way to find out if the user exists.

PS C:\> Get-ADUser –Filter {Surname –eq “Hess”}

     Figure 5: Querying AD for a user's surname.

You know that Surname is a good identifier to search on because it is part of the user record as shown in Figure 4 above. You can query AD using any of the identifiers listed. For example, you can use a user's given name, if you aren't sure of his or her surname.

PS C:\> Get-ADUser –Filter {GivenName –eq “Ken”}

    Figure 6: Querying AD using a user's given name.

This basic information will help you locate a user, if he or she exists in AD, but it doesn't tell you anything about the user's group memberships. For example, if a user is only supposed to be in the Domain Users group, the default for all domain users, but also has group membership in an Administrator group, you might never know until you query for that information.

PS C:\> Get-ADPrincipalGroupMembership –Identity khess

    Figure 7: Finding out to which groups a user belongs.

As Figure 7 shows, user khess belongs to Domain Users, Administrators, and Domain Admins.

You find that user khess isn't authorized to be a member of the Domain Admins group. You can revoke his membership to this group with the Remove-ADGroupMember cmdlet.

PS C:\> Remove-ADGroupMember –Identity “Domain Admins” –Member  “khess”

The system prompts you to agree that you want to take this action. Press Enter at the prompt to accept the default answer, which is "Yes."

To verify that you've successfully removed the user from the Domain Admins group, query AD for the user's principal group membership again.

PS C:\> Get-ADPrincipalGroupMembership –Identity khess

Figure 8 shows the results of the two cmdlets.
    Figure 8: Removing a user from the Domain Admins security group.

Working with Users and User Accounts

Creating new user accounts is one of the tasks that junior-level administrators receive as part of their standard duties. PowerShell’s AD cmdlets takes some of the pain out of creating them, although there is no known process for creating user accounts that is 100-percent painless. To create a new user account via PowerShell, you need to know two essential pieces of information: the correct spelling of the user’s name and the account name assigned to the user.

PS C:\> New-ADUser –Name “Abby Jones” –GivenName Abby –Surname Jones –UserPrincipalName ajones@mw.local –SamAccountName ajones

The cmdlet returns no information to you. Use the Get-ADUser cmdlet to confirm the account’s creation. See Figure 9 for details.

PS C:\> Get-ADUser ajones

    Figure 9: Creating a new user account.

Note that all AD accounts created via PowerShell are disabled by default unless you supply a password when you create the account. You will have to give the account a password and enable the account before the user can log on the first time. It’s easier to enable the account and supply a password at account creation, but some company policies require that new accounts remain disabled until the user has been assigned a computer.

One method of creating an enabled, password protected user account is to allow the script to ask you for a password, using the prompt supplied in the cmdlet (Password), as shown.

PS C:\> New-ADUser –Name “Abby Jones” –GivenName Abby –Surname Jones –UserPrincipalName ajones@mw.local –SamAccountName ajones –Enabled 1 –AccountPassword (Read-Host –AsSecureString “Password”)

Password: *********

To see a list of disabled accounts in the domain, use the Search-ADAccount cmdlet. See Figure 10.

PS C:\> Search-ADAccount –AccountDisabled –UserOnly |FT Name

    Figure 10: Listing the domain’s disabled accounts.

If you don’t specify “Enabled” and a password when you create the account, you’ll have to supply an initial password and enable the account as a two-step process.

First, change the user’s password from no password to the new password. Both passwords are read from keyboard input for security reasons. Since the user doesn’t have an old password, press ENTER when prompted for it.

PS C:\> Set-ADAccountPassword –Identity ajones –NewPassword (Read-Host –AsSecureString “New Password”) –OldPassword (Read-Host –AsSecureString “Old Password”)

New Password: ********
Old Password: <ENTER>

There’s no response from the system.

Enable the disabled account using the Enable-ADAccount cmdlet.

PS C:\> Enable-ADAccount –Identity ajones

You’re returned to the PowerShell prompt with no response. You can confirm that you successfully enabled the account.

PS C:\> Search-ADAccount –AccountDisabled –UserOnly |FT Name

The user’s name no longer appears in the list of disabled accounts.

As a System Administrator, you know that users sometimes lock themselves out of the domain by typing in a password incorrectly enough times that they exceed the maximum number of attempts and lockout occurs. Unlocking user accounts doesn’t have to be a stressful experience for you or the user, who’s locked himself or herself out of the domain. To unlock the user’s account, you need to have the user’s logon name, for example, khess.

You should first check to confirm that the user’s account is locked out.

PS C:\> Search-ADAccount –LockedOut –UsersOnly |FT Name

Name
----
Ken Hess

You find that the account is locked out. To unlock the account, issue the following cmdlet:

PS C:\> Unlock-ADAccount –Identity khess

The account is now unlocked and the user may logon.

To make the cmdlet interactive and useful to perform repeated unlocks, use the following cmdlet and save it as Unlock-Account.ps1.

PS C:\> Unlock-ADAccount –Identity (Read-Host “Username”)

You can run the script in PowerShell and it will prompt you for the user’s name and unlock the account.

Removing a user account is so easy to do that you should first disable the account. Disabling an account will render it useless unless another Administrator unlocks it, but it gives you time to verify that the user account should be removed from AD.

To disable a user account, use

PS C:\> Disable-ADAccount –Identity ajones

The system returns you to the PowerShell prompt with no response.

When you’re sure that the user account is ready for removal, use the Remove-ADUser cmdlet and answer the confirmation prompt.

PS C:\> Remove-ADUser ajones

    Figure 11: Removing a user account from Active Directory.

Working with Remote Domains

Near the beginning of this article, I told you that connecting to domains outside of your home domain can be done but it’s a bit clumsy. It is clumsy, but it can be done. The one thing that you have to remember is that you have to supply credentials for the remote domain for each cmdlet that you issue against it, otherwise your cmdlets operate on your home domain or will fail because you’re referencing resources unknown to your home domain.

For the purposes of this part of the article, MW.LOCAL is the remote, non-trusted domain. It is not my home domain and therefore I have to issue credentials for each command. For example, to look at the domain’s general information, use:

PS C:\> Get-ADDomain “MW.LOCAL” –Server “SERVER1” –Credential “MW.LOCAL\Administrator”

When you enter this cmdlet, you’ll receive a domain password prompt for the Administrator account as shown in Figure 12.
    Figure 12: Entering the Administrator password for the MW.LOCAL domain.

Once your credentials are accepted, the cmdlet executes against the remote domain and you receive your response as expected. See Figure 13.    Figure 13: Displaying Get-Domain results from a remote domain.

If you recall the simple, Get-ADUser khess cmdlet, the response displays information about the user’s account in the domain as shown in Figure 4.

The same cmdlet to query a remote domain requires a bit more information.

PS C:\> Get-ADUser khess –Server “SERVER1” –Credential “MW.LOCAL\Administrator”

Executing this cmdlet opens a password prompt for the MW.LOCAL domain. After authentication, you receive the response. See Figure 15.
    Figure 14: Displaying Get-ADUser results from a remote domain.

Note that PowerShell doesn’t cache your credentials. You’ll have to enter them each time you execute cmdlets against a remote domain in which you have authority.

There are other interesting cmdlets in the Active Directory module, such as those that: add computer service accounts, create new organization units, set password expiration, and move objects from one container to another or to a new domain.

In this brief introduction to PowerShell’s Active Directory module, you’ve learned to work with user accounts, to gather information about the domain, to examine user properties, to check group membership, to enter information into interactive cmdlets, and to connect to remote domains. The Active Directory PowerShell module offers System Administrators new opportunities for automating repetitive tasks and for streamlining domain activities.

Comments