Windows Advisor

5 Cool PowerShell Cmdlets for Speeding Up Active Directory Tasks

Five of my favorite PowerShell cmdlets that make it a breeze to work with Active Directory.

While I don't pretend to be an expert in Windows PowerShell scripting by any means, I use PowerShell whenever I can because I find it very useful to manage my servers. For network administrators who also manage Active Directory domain controllers, PowerShell scripting can be a great time-saver, especially in large enterprises. Fortunately, Microsoft has provided dozens of PowerShell cmdlets -- 76 to be exact -- for us to manage Active Directory. Here, I cover five of my favorites.

I should point out that you cannot run the Active Directory cmdlets from the standard Windows PowerShell utility. You must install the Active Directory module for Windows PowerShell.

What is Active Directory Module for Windows PowerShell?
Microsoft has packaged all 76 cmdlets that we can use with Active Directory on Windows Server 2008 R2 in a single package and named it "Active Directory." The cmdlets in this self-contained package can be used to manage your Active Directory domains, Active Directory Lightweight Directory Services (AD LDS) configuration sets, and Active Directory Database Mounting Tool instances.

The Active Directory Module for Windows PowerShell lets you manage or create new user and computer accounts, groups, organizational units (OUs), domains and forests, domain controllers, and password policies. By default, this module is available for use with Windows Server 2008 R2 Standard, Enterprise and Datacenter editions, as well as Windows 7. The module is not available Windows Server 2008 R2 for Itanium-Based Systems or Windows Web Server 2008 R2.

You can access Active Directory Module for Windows PowerShell from the Administrative Tools menu. On a Windows Server 2008 R2 go to Start | Administrative Tools | Active Directory Module for Windows PowerShell. On a Windows 7 PC, you can install Remote Server Administration Tools (RSAT), which includes the Active Directory module. However, after you install RSAT, you still need to install the Active Directory module because it doesn't install it by default.

To be frank, there are too many of these cmdlets that I find useful, but in the interest of brevity, these five are the ones I figured would be most interesting to you. You will notice that the cmdlets in the Active Directory module are fairly self-explanatory. They begin with Add, Clear, Disable, Enable, Get, Install, Move, New, Remove, Rename, Reset, Restore, Search, Set, Uninstall, and Unlock. The Get cmdlet simply retrieves the information from Active Directory, while the Set cmdlet is used to modify the information in the existing objects.

One nice thing about PowerShell cmdlets is that all the help is built-in. To get help you can type Get-Help <cmdlet name>. For example, Get-Help Get-ADGroupMember will show the help fo the ADGroupMember cmdlet. You can also use the options -Detailed, -Full and -Examples. For example, Get-Help Get-ADGroupMember -Detailed dives deeper into the cmdlet.

CAUTION! As a best practice, I do not recommend experimenting with these cmdlets on a production server, unless you have tested them thoroughly in a test environment. Some of these cmdlets may not do any harm, but others can potentially cause serious damage and get you into career-ending trouble if not executed properly.

1. Get-ADGroupMember
The Get-ADGroupMember cmdlet retrieves the members of an Active Directory group. The members can be users, groups, or computers:

Get-ADGroupMember [-Identity] <ADGroup> [-AuthType {<Negotiate> | <Basic>}] [-Credential <PSCredential>] [-Partition <string>] [-Recursive <switch>] [-Server <string>] [<CommonParameters>]

  • Identity: Active Directory group. You can identify a group by its distinguished name (DN), GUID, security identifier (SID), or Security Accounts Manager (SAM) account name. I prefer to use SAM account name.
  • AuthType: Authentication method. Options are Negotiate (0) and Basic (1). The default is Negotiate. The Basic authentication method requires an SSL connection.
  • Credential: Specifies the user account credentials to use to perform this task. By default it uses the credentials of the account that is currently logged on.
  • Partition: Distinguished name of an Active Directory partition. For example, the configuration or the schema partition.
  • Recursive: This option specifies that the cmdlet get all the members in the hierarchy of a group that do not contain child objects.
  • Server: Active Directory Domain Services instance that you will be connecting to. Here you can use a fully qualified domain name (FQDN), or a NetBIOS name of the Active Directory domain or the Active Directory server.

To list all the accounts that are included in the Administrators group, type this:

get-adgroupmember -Identity administrators

This can come handy when you want to quickly keep an eye on the Administrators group, to ensure there are no unexpected members. The results will give you the DN, GUID, SID, SamAccountName, etc. for all the members.

Here's another example to get all the members of the Domain Admins group including the members of any child groups:

get-adgroupmember "Domain Admins" -recursive

Besides listing the group members, you can also add individuals to the group by using the Add-ADGroupMember cmdlet.

2. New-ADComputer
The New-ADComputer cmdlet lets you add a new computer to the Active Directory domain. Keep in mind that adding doesn't mean "joining" the domain. There are several situations where pre-created computer objects can be useful. For example, you can create computer accounts for use in offline domain join; unsecure domain join and Read-Only Domain Controller (RODC) domain join scenarios. Here's the syntax:

New-ADComputer [-Name] <string> [-AccountExpirationDate <System.Nullable[System.DateTime]>] [-AccountNotDelegated <System.Nullable[bool]>] [-AccountPassword <SecureString>] [-AllowReversiblePasswordEncryption <System.Nullable[bool]>] [-AuthType {<Negotiate> | <Basic>}] [-CannotChangePassword <System.Nullable[bool]>] [-Certificates <X509Certificate[]>] [-ChangePasswordAtLogon <System.Nullable[bool]>] [-Credential <PSCredential>] [-Description <string>] [-DisplayName <string>] [-DNSHostName <string>] [-Enabled <System.Nullable[bool]>] [-HomePage <string>] [-Instance <ADComputer>] [-Location <string>] [-ManagedBy <ADPrincipal>] [-OperatingSystem <string>] [-OperatingSystemHotfix <string>] [-OperatingSystemServicePack <string>] [-OperatingSystemVersion <string>] [-OtherAttributes <hashtable>] [-PassThru <switch>] [-PasswordNeverExpires <System.Nullable[bool]>] [-PasswordNotRequired <System.Nullable[bool]>] [-Path <string>] [-SAMAccountName <string>] [-Server <string>] [-ServicePrincipalNames <string[]>] [-TrustedForDelegation <System.Nullable[bool]>] [-UserPrincipalName <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

  • Name: The name of the computer object.
  • AccountExpirationDate: Expiration date for the account.
  • AccountNotDelegated: Whether the security context of the user is delegated to a service. $true or 1 means not delegated, $false or 0 means it is delegated.
  • AccountPassword: Password for the account. If not password is specified then a random password is set and the account is enabled.
  • AllowReversiblePasswordEncryption: Specifies whether reversible password encryption is allowed for the computer object. $true or 1 means reversible password encryption is allowed, $false or 0 means it is not allowed.
  • AuthType: Authentication method that will be used. Options are Negotiate (0) and Basic (1). The default is Negotiate. The Basic authentication method requires an SSL connection.
  • CannotChangePassword: Whether the account password can be changed. $true or 1 will allow password to be changed, $false or 0 will prohibit it.
  • Certificates: Modifies the DER-encoded X.509v3 certificates of the account. The certificates include the public key certificates issued to this account by the Microsoft Certificate Service.
  • ChangePasswordAtLogon: Whether a password must be changed during the next logon attempt. $true or 1 will require the password to be changed (unless the PasswordNeverExpires property has been set to true), $false or 0 will not require that password be changed at next logon. Generally this parameter is used for user accounts, rather than computer accounts.
  • Credential: Specifies the user account credentials to use to perform this task. By default it uses the credentials of the account that is currently logged on.
  • Description: A description of the computer object.
  • DisplayName: The display name of the object.
  • DNSHostName: A fully qualified domain name (FQDN) of the computer object.
  • Enabled: Whether the account is enabled. An enabled account requires a password. $true or 1 sets it to enabled, $false or 0 sets it to disabled.
  • HomePage: The URL of the home page of the object.
  • Instance: An instance of a computer object to use as a template for a new computer object.
  • Location: Location of the computer, such as building or lab number.
  • ManagedBy: The user or group that manages the object.
  • Name: The name of the computer object, such as SalesPC1.
  • OperatingSystem: An operating system name, such as Windows 7 Ultimate.
  • OperatingSystemHotfix: An operating system hotfix name.
  • OperatingSystemServicePack: The name of an operating system service pack, such as Service Pack 1.
  • OperatingSystemVersion: An operating system version.
  • OtherAttributes: Object attribute values for attributes that are not represented by cmdlet parameters.
  • PassThru: Returns the new or modified object. By default this cmdlet does not generate any output if the PassThru parameter is not specified.
  • PasswordNeverExpires: Whether the password of an account can expire. $true or 1 will set the password to never expire, $false or 0 will set it to expire.
  • PasswordNotRequired: Whether the account requires a password. $true or 1 will not require a password, $false or 0 will require a paswsword.
  • Path: The X.500 path of the Organizational Unit (OU) or container where the new object is created. You can use the path to create the object in a specific OU.
  • SAMAccountName: The Security Account Manager (SAM) account name of the computer. Although you can use up to 256 characters, it is best not to exceed 20 characters for backward compatibility with older operating systems.
  • Server: Active Directory Domain Services instance that you will be connecting to. Here you can use a fully qualified domain name (FQDN), or a NetBIOS name of the Active Directory domain or the Active Directory server.
  • ServicePrincipalNames: This parameter sets the ServicePrincipalNames property of the account.
  • TrustedForDelegation: Whether the computer account is trusted for Kerberos delegation. $true or 1 will set it to be trusted, $false or 0 will not set it to be trusted for delegation.
  • UserPrincipalName: A user principal name (UPN) for the object.
  • Confirm: Prompts you for confirmation before you execute the command.
  • WhatIf: Used for what if scenarios. What would happen if you executed the command without actually executing the command?

Here's an example for creating a computer object:

New-ADComputer -Name "SalesPC1" -SamAccountName "SalesPC1" -Path "OU=Computers,OU=Sales,DC=Contoso,DC=com" -Enabled $true -Location "Seattle,WA"

This creates a computer called SalesPC1 in the Computer OU that is located in the Sales OU in the Contoso.com domain. The computer object will be enabled and the location of the computer will be set to Seattle, WA. The location is displayed on the Location tab of the computer object when you look at its properties.

If you set the -AccountExpirationDate parameter to 0 (zero), the account will never expire. Yes, you can use the DateTime parameter to set an expiration date and time for a computer object. If you hire a temporary employee for 90 days, you can create a computer account for her and set the expiration date so the computer account expires in 90 days at 5:00:00 PM local time. If you don't set the time it defaults to 12:00:00 AM local time.

3. Remove-ADUser
Remove-ADUser cmdlet removes an Active Directory user. You can identify a user by its DN, GUID, SID or SAM account name. One common use of this cmdlet is to use the Get-ADUser cmdlet to retrieve a user account and then pipe the object through to the Remove-ADUser cmdlet, as I explain after the syntax and attributes:

Remove-ADUser [-Identity] <ADUser> [-AuthType {<Negotiate> | <Basic>}] [-Credential <PSCredential>] [-Partition <string>] [-Server <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

  • Identity: Specifies an Active Directory user object by providing one of the following property values: Distinguished Name, GUID, SID, or samAccountName.
  • AuthType: Authentication method. Options are Negotiate (0) and Basic (1). The default is Negotiate. The Basic authentication method requires an SSL connection.
  • Credential: Specifies the user account credentials to use to perform this task. By default it uses the credentials of the account that is currently logged on.
  • Partition: Distinguished name of an Active Directory partition. For example, the configuration or the schema partition.
  • Server: Active Directory Domain Services instance that you will be connecting to. Here you can use a fully qualified domain name (FQDN), or a NetBIOS name of the Active Directory domain or the Active Directory server.
  • Confirm: Prompts you for confirmation before you execute the command.
  • WhatIf: Used for what if scenarios. What would happen if you executed the command without actually executing the command?

The Search-ADAccount cmdlet can be very useful for searching for all disabled accounts that you want to remove. Here's how:

Search-ADAccount -AccountDisabled | where {$_.ObjectClass -eq 'user'} | Remove-ADUser

As mentioned earlier, use caution when executing some of these cmdlets on your production servers. With that in mind, then you can type this:

Remove-ADUser -Identity JohnSmith

to remove a user named John Smith, where JohnSmith is the samAccountName.

4. Set-ADAccountPassword
Use the Set-ADAccountPassword cmdlet to set the password for an Active Directory account. As I said earlier, the cmdlets that start with "Set" are used to modify the information on existing objects.

You can either use Search-ADAccount cmdlet to retrieve an account or use the Get cmdlet (Get-ADUser, Get-ADComputer, Get-ADServiceAccount), then you can pass the object through the pipeline to the Set-ADAccountPassword cmdlet. Normally you would use the OldPassword and the NewPassword parameters to set the password, unless you use the Reset parameter, which doesn't require you to specify the old password.

Here's the syntax:

Set-ADAccountPassword [-Identity] <ADAccount> [-AuthType {<Negotiate> | <Basic>}] [-Credential <PSCredential>] [-NewPassword <SecureString>] [-OldPassword <SecureString>] [-Partition <string>] [-PassThru <switch>] [-Reset <switch>] [-Server <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

  • Identity: Active Directory account, such as user, computer or service account. You can identify the account by its DN, GUID, SID, or samAccountName.
  • AuthType: Authentication method. Options are Negotiate (0) and Basic (1). The default is Negotiate. The Basic authentication method requires an SSL connection.
  • Credential: Specifies the user account credentials to use to perform this task. By default it uses the credentials of the account that is currently logged on.
  • NewPassword: Specifies a new password value that is stored as an encrypted string.
  • OldPassword: Specifies the most recent password value that is processed as an encrypted string.
  • Partition: Distinguished name of an Active Directory partition. For example, the configuration or the schema partition.
  • PassThru: Returns the new or modified object. By default this cmdlet does not generate any output if the PassThru parameter is not specified.
  • Reset: Resets the password for an account. You do not need to specify the OldPassword parameter when you use this cmdlet. You only need to specify the NewPassword parameter.
  • Server: Active Directory Domain Services instance that you will be connecting to. Here you can use a fully qualified domain name (FQDN) or a NetBIOS name of the Active Directory domain or the Active Directory server.
  • Confirm: Prompts you for confirmation before you execute the command.
  • WhatIf: Used for what if scenarios. What would happen if you executed the command without actually executing the command?

To set the password for a user named Bill Gates, whose SAM account name is BillG, type this:

Set-ADAccountPassword -Identity BillG

If the full name of the user is Bill Gates and the samAccountName is BillG, this is what the output might look like:

Set-ADAccountPassword -Identity BillG
Please enter the current password for 'CN=Bill Gates,OU=Executives,DC=Contoso,DC=com'
Password: ********
Please enter the desired password for 'CN=Bill Gates,OU=Executives,DC=Contoso,DC=com'
Password: ********
Repeat Password: ********

Note that CN, which refers to Common Name, is really what Microsoft calls a Full Name of the account. Because all the accounts must be unique across the Active Directory domain, when you use the SAM account name there is no need to specify the full path (DN) to the account. That's why I prefer to use the SAM account name over other options.

5. Unlock-ADAccount
The cmdlet Unlock-ADAccount unlocks an Active Directory account. A user account can get locked if the number of incorrect password retries exceeds the maximum number of attempts allowed by the account password policy. An administrator can unlock the account. You can identify an account by its distinguished name (DN), GUID, security identifier (SID), or Security Accounts Manager (SAM) account name.

Similar to the previous example, you can either use the Search-ADAccount cmdlet to retrieve an account or use the Get cmdlet (Get-ADUser, Get-ADComputer, Get-ADServiceAccount), then pass the object through the pipeline to the Unlock-ADAccount cmdlet to unlock the account.

Note: The Unlock-ADAccount cmdlet does not work with an Active Directory Snapshot or with a read-only domain controller.

Here's the complete syntax:

Unlock-ADAccount [-Identity] <ADAccount> [-AuthType {<Negotiate> | <Basic>}] [-Credential <PSCredential>] [-Partition <string>] [-PassThru <switch>] [-Server <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

  • Identity: The Active Directory account to unlock. You can identify an account by its distinguished name (DN), GUID, security identifier (SID), or Security Accounts Manager (SAM) account name.
  • AuthType: Authentication method. Options are Negotiate (0) and Basic (1). The default is Negotiate. The Basic authentication method requires an SSL connection.
  • Credential: Specifies the user account credentials to use to perform this task. By default it uses the credentials of the account that is currently logged on.
  • Partition: Distinguished name of an Active Directory partition. For example, the configuration or the schema partition.
  • PassThru: Returns the new or modified object. By default this cmdlet does not generate any output if the PassThru parameter is not specified.
  • Server: Active Directory Domain Services instance that you will be connecting to. Here you can use a fully qualified domain name (FQDN) or a NetBIOS name of the Active Directory domain or the Active Directory server.
  • Confirm: Prompts you for confirmation before you execute the command.
  • WhatIf: Used for what if scenarios. What would happen if you executed the command without actually executing the command?

To unlock an account, I prefer to use the SAM account name rather than using the DN. For example, use this command:

Unlock-ADAccount -Identity BillG

to unlock the Bill Gates account whose SAM account name is BillG.

As you can see, the Active Directory module for Windows PowerShell for Windows Server 2008 R2 has dozens of cmdlets that can be useful in managing your Active Directory. If you are an experienced PowerShell user, you will be able to run these scripts in your sleep. PowerShell newbies will discover that once you've used a few of these cmdlets, you'll wonder how you got along with 'emThey are really simple to use and after a while, you won't even have to look up the syntax for most of them.

For a complete listing of all the Active Directory cmdlets in Windows PowerShell that are available in Windows Server 2008 R2 you can click here. For additional information check out the Cmdlet Reference for Windows Server 2008 R2 on Microsoft TechNet. There you will find cmdlets for Group Policies, Active Directory Federation Services (ADFS) ;2.0 and more.

What Active Directory cmdlets have been the most helpful to you? Share them here.

comments powered by Disqus
Most   Popular