Using PowerShell to Manage AD and AD Users

Installing Active Directory and Creating a New Forest

The initial task is to install Active Directory Domain Services (AD DS) role. AD DS is installed by running the following PowerShell command:

Figure 1

Running the script below completes the installation of the first domain controller in a new Active Directory Forest.

Import-Module ADDSDeployment

Install-ADDSForest `

-CreateDnsDelegation:$false `

-DatabasePath “C:\Windows\NTDS” `

-DomainMode “Win2012R2” `

-DomainName “LanzTek.local” `

-DomainNetbiosName “LANZTEK” `

-ForestMode “Win2012” `

-InstallDns:$true `

-LogPath “C:\Windows\NTDS” `

-NoRebootOnCompletion:$false `

-SysvolPath “C:\Windows\SYSVOL” `


This script is helpful in a Server core installation where you do not have direct access to the Windows graphical interface to install AD DS.

Only two cmdlets: Import-Module and Install-ADDSForest are used in this script. The Import-Module adds the ADDSDeployment module to the current session making all the cmdlets associated with that module available as long as the session remains open. In PowerShell 3.0 and above, installed modules are automatically imported to a session when a cmdlet that corresponds to a particular module is used.

The Install-ADDSForest cmdlet installs AD DS on a Windows Server 2012 R2 server and creates a new Active Directory forest configuration. Let’s review the Install-ADDSForest parameters used in this script:

-CreateDnsDelegation:$false – Because the domain controller is also going to be configured as a DNS server, this parameter is used to signal whether a DNS delegation references this new DNS server and its name space.

-DatabasePath “C:\Windows\NTDS” – Specifies the location of the Active Directory database.

-DomainMode “Win2012R2″ – Defines the domain functional level for the first domain in the new forest. This parameter can be either a string or an integer value. The following options are supported:

* Windows Server 2012 R2: Win2012R2 or 6

* Windows Server 2012: Win2012 or 5

* Windows Server 2008 R2: Win2008R2 or 4

* Windows Server 2008: Win2008 or 3

* Windows Server 2003: Win2003 or 2

-DomainName “LanzTek.local” – This is the fully qualified domain name for the root domain in the forest.

-DomainNetbiosName “LANZTEK” – Designates the NetBIOS name for the root domain. Even if you do not plan to use any NetBIOS applications, this parameter must be configured with a valid single label name that contains no more than 15 characters. If the NetBIOS name is more than 15 characters, the forest installation fails.

-ForestMode “Win2012″ – This parameter defines the forest functional level for the new forest. It supports the same value options as the DomainName parameter.

-InstallDns:$true – Specifies that the DNS Server service will be installed in this domain controller. By default, a new Active Directory Integrated DNS zone is created with the name of the domain. In this case, lanztek.local.

-LogPath “C:\Windows\NTDS” – Specifies the location of AD DS log files.

-NoRebootOnCompletion:$false – Indicates whether to reboot the server after completion. A reboot is necessary for the new domain controller to become fully functional.

-SysvolPath “C:\Windows\SYSVOL” – Specifies the location of the Sysvol folder. A sysvol networkshare is automatically created within the Sysvol folder as part of the AD DS installation process.

-Force:$true – This parameter mutes any normal warning that is generated during the installation.

Active Directory Module for Windows PowerShell

After running the script, an Active Directory module for Windows PowerShell is installed on the domain controller. This module is automatically imported into a PowerShell session any time you try to use one of its cmdlets. By using implicit remoting, this module can be imported into a Windows client or a Windows Server computer that does not have active directory installed and from there you could perform remote administration of active directory. This module is also available as part of the Remote server Administration Tools that can be installed on Windows 7 or Windows 8 clients as well as member servers running Windows server 2008 R2, Windows 2012 or Windows 2012 R2. The AD module uses the Active Directory Web Services (ADWS) service to communicate and manage the active directory. Incidentally, the Active Directory Administrative Center (ADAC) is a graphical interface that sits on top of Windows PowerShell so it also needs ADWS to function.

Active Directory PowerShell Drive (PSDrive) Provider

The Active Directory module includes a PSDrive provider that allows you to look through the content of the directory in a way that is very similar to how you navigate the file system. Importing the AD module maps a drive named AD: to the domain to which you are currently logged on. This drive provides a security framework for executing the cmdlets. Each time you execute an active directory cmdlet, PowerShell automatically uses the credentials and domain of the currently mapped PSDrive. Without this functionality you would need to enter credentials every time you run an active directory cmdlet or script. To see the content of the AD PSDrive, run this command:

Get-ChildItem AD:

Figure 2

The output shows all the active directory partitions. From there, you can navigate deeper into any of these partitions to verify configurations or make changes to AD objects. For example, let’s look into the domain partition by executing this command:

Get-ChildItem AD:\”dc=lanztek,dc=local”

Figure 3

To see only the users accounts within the Users container, run:

Get-ChildItem AD:\”cn=users,dc=lanztek,dc=local” | ? {$_.objectClass -eq “user”}

Figure 4

Now, let’s say that we want to make a change on the Administrator account by modifying the department property value. This command will do the trick:

Set-ItemProperty -Path AD:\”cn=Administrator,cn=users,dc=lanztek,dc=local” `

-Name “Department” -Value “Information Technology”

Figure 5

On the previous command the –path is used to point to the location of the Administrator account inside the Users container. The –Name parameter indicates the property to modify, in this case the department, and finally the –Value parameter indicates the department label or designation for that user.

Using this command is possible to verify the change:

Get-ADUser administrator -Properties * | Format-List DistinguishedName,Name,Department

Figure 6

As we could see in the preceding examples, it is possible to manage the active directory by having direct access to the AD PSDrive. However, using the Active Directory module for Windows PowerShell cmdlets is a more pragmatic approach to automate many AD administration tasks.

Creating and Enabling AD User Accounts

Let’s start by creating a user account using the New-ADUser cmdlet:

New-ADUser -Name “Will Lanz” -SamAccountName “wlanz”`

-GivenName “Will” -Surname “Lanz” -DisplayName “Will Lanz”`

-UserPrincipalName “[email protected]` -Path “OU=Sales,DC=lanztek,DC=local”

-Department “IT”

This command creates a user account in the Sales Organizational Unit on the lanztek.local domain. However, no password has been entered and the account would be disabled. To verify that the account was created, run this command:

Get-ADUser wlanz

Figure 7

Let’s create a password and enable the wlanz account by executing the code below:

Set-ADAccountPassword -Identity wlanz -Reset -NewPassword`

(ConvertTo-SecureString -AsPlainText “Pa$$w0rd” -Force)

Enable-ADAccount -Identity wlanz

It is important to notice that for security reasons PowerShell does not pass a plaintext password to active directory without encryption. The –NewPassword parameter must store its value as an encrypted string. In this case, the ConvertTo-SecureString cmdlet is used to convert the plain text password to a secure string. The –AsPlainText parameter specifies that the plain text string “Pa$$w0rd” must be converted to a secure string. This ensures that the text will be encrypted and deleted from the computer memory after it is no longer needed. The –Force parameter is used in conjunction with the –AsPlainText parameter to confirm the encrypting process.

To verify that the account has been enabled, run this command again:

Get-ADUser wlanz

Figure 8

Creating a user account and enabling it later may be necessary in some situations, but in many cases you may want to create and enable the account as part of the same process. Let’s do that next by running these commands:

New-ADUser -Name “Vito Corleone” -SamAccountName “Vcorleone” `

-GivenName “Vito” -Surname “Corleone” -DisplayName “Vito Corleone” `

-UserPrincipalName “[email protected]” -Enabled $true `

-Path “OU=Sales,DC=lanztek,DC=local” -Department “Sales” `

-AccountPassword (ConvertTo-SecureString “Pa$$w0rd”`

-AsPlainText -Force)

In the preceding code we used the New-ADUser cmdlet again, but this time two parameters –AccountPassword and –Enabled were added to securely configure a password and to enable the account.

Managing Multiple AD User Accounts

Hundreds and even thousands of user accountants can be created and managed in Active Directory with a few lines of code. Let’s demonstrate this procedure by importing the user names and properties from a comma-separated value (CSV) file. Let’s say that you need to create several user accounts, you can generate a CSV file with all the accounts’ information and use the Import-CSV cmdlet to import and then pipe that data to the New-ADUser cmdlet. The New-ADUser cmdlet picks up all the parameters names and values from the PowerShell pipeline and creates the user accounts in the directory. The figure below shows the CSV file used in our demonstration.

Figure 9

As you can see, the column headers match parameter names available with the New-ADUser cmdlet.

Once the CSV file is ready, running the following script will create all the user accounts in the directory.

Import-Csv -Path c:\scripts\users\users.csv |

foreach {New-ADUser -Name $ -Enabled $true `

-AccountPassword (ConvertTo-SecureString $_.password `

-AsPlainText -Force) `

-SamAccountName $_.samAccountName -City $ `

-Department $_.Department -EmployeeID $_.EmployeeID `

-Path “OU=sales,DC=lanztek,DC=local”}

The Foreach is used here to loop through the data one row at a time. For each row, a new AD user account is created by the New_ADUser cmdlet. The scripts direct PowerShell to create the user accounts in the Sales Organizational Unit on the lanztek.local domain.

Let’s verify that the user accounts were created in the Sales OU by executing this code:

Get-ADUser -Filter * -SearchBase “OU=sales,dc=lanztek,dc=local” |

Format-table Name,Distinguishedname,Enabled -AutoSize

Figure 10

Once the user accounts are created, many managing and maintenance tasks can be automated using Windows PowerShell. For example, the figure above shows that there are nine accounts in the Sales OU. Let’s say that we want to move all these users to the Finance OU. This code will complete the task:

Get-ADUser -Filter * -SearchBase “OU=sales,dc=lanztek,dc=local” |

Move-ADObject -TargetPath “OU=Finance,DC=lanztek,DC=local”

There may be other AD objects in the Sales OU, but the preceding code uses the Get-ADUser cmdlet to pull only the user accounts from the Sales OU and pipe the results to the Move-ADObject cmdlet. The Move-ADObject cmdlet in turn executes the relocation of the accounts to the Finance OU.

By using the user accounts properties it is possible to quickly find users in the directory that meet specific criteria on the PowerShell search. For example, we want to find AD users who work in the Operations department and live either in Denver or Dallas. The code to search for the data is:

Get-ADUser -Filter `

‘(city -eq “denver” -or city -eq “Dallas”) -and (department –eq “operations”)’ `

-properties * | Select-Object Name,Department,City

Here are the results:

Figure 11

Managing AD users and Groups is also more efficient with PowerShell. Let’s say that we want to find all the users who work in the Operations department and add them to a group named Operations. See the code below:

$OpsUsers = Get-ADUser -Filter ‘department -eq “Operations”‘

Add-ADGroupMember -Identity operations -Members $OpsUsers

The –Members parameter of the Add-ADGroupMember does not accept pipeline input. To go around that inconvenience, the $OpsUsers variable is created to collect all the users who work in the Operations department. Then we pass that variable directly to the –Members parameter to add those users to the Operations group.

This code will verify the membership of the Operations group:

Get-ADGroupMember -Identity Operations |

FT name,DistinguishedName -AutoSize

Closing remarks

This article focused on using Windows PowerShell to install Active Directory Domain Services and manage AD user accounts. Once AD DS is installed, the Active Directory Module for Windows PowerShell is available along with an AD PSdrive that provides a security context to run the AD related cmdlets. With over 140 cmdlets, this module is a powerful tool to administer and automate tasks associated not only to AD user accounts, but to all other AD objects as well. Being able to perform these jobs from a remote computer is probably one of the best capabilities of Windows PowerShell. I purposely omitted talking about PowerShell remoting because that is the main topic in our next article in this PowerShell series.

This article was originally published by InfoSec Institute.

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top