Home > Sample chapters

Create and Manage Users and Groups in Active Directory

In this chapter from Deploying and Managing Active Directory with Windows PowerShell: Tools for cloud-based and hybrid environments, learn how to create and manage users, groups, and OUs; how to filter against the properties of users, groups, and computers to selectively act on the results of that filter; and how to add users to groups and move users and computers into an OU.

Now that we have a forest and domain, and we’ve got the basics of networking and name resolution sorted, the next step is to add some users to our domain. We’ll start with adding a simple user, interactively, and then create a bunch of users by using a script and a comma-separated values (CSV) file. We’ll create a new group and then add a group of users into that group, using a filter to ensure that we add the correct set of users. Then we’ll create a new organizational unit (OU) and move users and computers into the OU. Pretty basic stuff, really, but essential for any domain administrator.

Active Directory Windows PowerShell nouns used in this chapter:

  • ADUser
  • ADGroup
  • ADGroupMember
  • ADAccountPassword
  • ADPrincipalGroupMembership
  • ADObject
  • ADComputer

Other Windows PowerShell commands used in this chapter:

  • Import-CSV
  • ConvertTo-SecureString
  • Get-Command
  • Test-Path
  • Read-Host
  • Write-Host

Create users

Use the New-ADUser cmdlet to create new users. Most user properties can be directly added by using the parameters of New-ADUser detailed in Table 3-1, shown later in this section. Those user attributes not explicitly available as direct parameters to New-ADUse can be added by using the OtherAttributes parameter, which accepts a hashtable of attribute names and values.

Create a single user

The first thing you’ll want to do for your new domain is create an administrative user that isn’t ”Administrator.” That first Administrator account is sometimes referred to as the 500 account because the last three digits of its security identifier (SID) are 500, as we can tell from a quick Get-ADUser.

Get-ADUser -Identity Administrator
DistinguishedName : CN=Administrator,CN=Users,DC=TreyResearch,DC=net
Enabled           : True
GivenName         :
Name              : Administrator
ObjectClass       : user
ObjectGUID        : a196f5de-343f-48d5-8aab-5289bfa6fabc
SamAccountName    : Administrator
SID               : S-1-5-21-910751839-3601328731-670513855-500
Surname           :
UserPrincipalName :

The 500 account is a bit too well known to use for everyday administration and should be given a really long and onerous password that is locked away somewhere very secure and then left alone except in dire emergencies. So let’s give ourselves a working administrative account, and then we’ll change the password on the 500 account and retire it from everyday use.

To add a new user, use the New-ADUser cmdlet. There are three basic ways to use New-ADUser:

  1. Create a user by specifying all details on the command line.
  2. Create a user from a template object“either one you create or an existing user.
  3. Use a CSV file to create multiple users from a list of users and properties.

We’re going to use option #1 to create our first administrative user. We need to specify the settings for the new user at the command line. Then we need to add the user to the appropriate Active Directory Domain Services (AD DS) security groups. First, to create the user, ”Charlie,” use the following commands.

$SecurePW = Read-Host -Prompt “Enter a password” -asSecureString
New-ADUser -Name “Charlie Russel” `
           -AccountPassword $SecurePW  `
           -SamAccountName 'Charlie’ `
           -DisplayName 'Charlie Russel’ `
           -EmailAddress 'Charlie@TreyResearch.net’ `
           -Enabled $True `
           -GivenName 'Charlie’ `
           -PassThru `
           -PasswordNeverExpires $True `
           -Surname 'Russel’ `
           -UserPrincipalName 'Charlie’

The Read-Host in the previous code prompts for a password and masks what the user enters, and the result of the New-ADUser command is displayed at the console because I used the -PassThru parameter, as shown in Figure 3-1.

Figure 3-1

Figure 3-1 Creating a new user by using New-ADUser

This creates our first user but doesn’t make the user a member of any domain security groups except Domain Users, the default. To add the user to security groups, we need to use the Add-ADGroupMember cmdlet. And because the goal is to give Charlie the same set of security groups as the Administrator account, we’ll use Windows PowerShell to get the list of security groups that the Administrator is a member of, and then loop through the list and add Charlie to each of the groups.

$SuperUserGroups = @()  
$SuperUserGroups = (Get-ADUser -Identity “Administrator” -Properties * ).MemberOf

ForEach ($Group in $SuperUserGroups ) {
   Add-ADGroupMember -Identity $Group -Members “Charlie” 
}

(Get-ADUser -Identity Charlie -Properties *).MemberOf
CN=Group Policy Creator Owners,CN=Users,DC=TreyResearch,DC=net
CN=Domain Admins,CN=Users,DC=TreyResearch,DC=net
CN=Enterprise Admins,CN=Users,DC=TreyResearch,DC=net
CN=Schema Admins,CN=Users,DC=TreyResearch,DC=net
CN=Administrators,CN=Builtin,DC=TreyResearch,DC=net

As we can tell from the Get-ADUser command in the previous code, the account Charlie is now a member of five security groups: Group Policy Creator Owners, Domain Admins, Enterprise Admins, Schema Admins, and Administrators. These are the same security groups to which the Administrator account belongs. We’ll want to come back to AD DS groups later, but let’s focus on users first.

In the creation of this first user, we used the most common parameters of the New-ADUser cmdlet, but they’re only a fraction of the options available. Your situation might well require you to add significantly more information to each AD DS account. The available parameters for New-ADUser that relate to users are listed in Table 3-1.

Table 3-1 The user property parameters of New-ADUser

Parameter

Type

Name

String

AccountExpirationDate

Datetime

AccountNotDelegated

Boolean

AccountPassword

SecureString

AllowReversiblePasswordEncryption

Boolean

AuthenticationPolicy

ADAuthenticationPolicy

AuthenticationPolicySilo

ADAuthenticationPolicySilo

AuthType

ADAuthType

CannotChangePassword

Boolean

Certificates

X509Certificate[]

ChangePasswordAtLogon

Boolean

City

String

Company

String

CompoundIdentitySupported

Boolean

Country

String

Credential

PSCredential

Department

String

Description

String

DisplayName

String

Division

String

EmailAddress

String

EmployeeID

String

EmployeeNumber

String

Enabled

Boolean

Fax

String

GivenName

String

HomeDirectory

String

HomeDrive

String

HomePage

String

HomePhone

String

Initials

String

Instance

ADUser

KerberosEncryptionType

ADKerberosEncryptionType

LogonWorkstations

String

Manager

ADUser

MobilePhone

String

Office

String

OfficePhone

String

Organization

String

OtherAttributes

Hashtable

OtherName

String

PassThru

Switch

PasswordNeverExpires

Boolean

PasswordNotRequired

Boolean

Path

String

POBox

String

PostalCode

String

PrincipalsAllowedToDelegateToAccount

ADPrincipal[]

ProfilePath

String

SamAccountName

String

ScriptPath

String

Server

String

ServicePrincipalNames

String[]

SmartcardLogonRequired

Boolean

State

String

StreetAddress

String

Surname

String

Title

String

TrustedForDelegation

Boolean

Type

String

UserPrincipalName

String

Add users in a batch

There are multiple ways to add users in a batch, but probably the simplest is to use a CSV file. You can easily create the CSV file in Microsoft Excel or any plain text editor, and then use Windows PowerShell to read the values in the CSV file and add the users. In my lab, all my animals have their own domain accounts, so I’ll use them to show how to quickly and easily create new users. All are initially created as Domain Users, with a default password, and then one account gets elevated and prompts for a password. The list of users and their basic properties are in the following code.

TreyUsers.csv
Name,GivenName,Surname,DisplayName,SAMAccountName,Description
David Guy,David,Guy,Dave R. Guy,Dave,Customer Appreciation Manager
Alfredo Fettucine,Alfredo,Fettuccine,Alfie NoNose,Alfie,Shop Foreman
Stanley Behr,Stanley,Behr,Stanley T. Behr, Stanley,WebMaster
Priscilla Catz,Priscilla,Catz,Dame Priscilla,Priscilla,Shop Steward
Harold Catz,Harold,Catz,Harold S. Catz,Harold,Engineering Manager
William Wallace,William,Wallace,Sir William Wallace,Wally,Marketing Manager
Trey Barksdale,Trey,Barksdale,Lord Barksalot,Trey,Sales Manager
Charlie Russel,Charlie,Russel,Charlie Russel,Charlie,SuperUser Account

As you can tell, I’ve only used the most basic information for each new user. To read the CSV file, use the Import-CSV cmdlet, and then loop through each user from the CSV file and create the user with New-ADUser by using a basic ForEach loop.

Create-TreyUsers.ps1

<#
.Synopsis
Creates the TreyResearch.net users
.Description
Create-TreyUsers reads a CSV file to create an array of users. The users are then added 
to the users container in Active Directory. Additionally, Create-TreyUsers adds the 
user Charlie to the same AD DS Groups as the Administrator account.
.Example
Create-TreyUsers
Creates AD Accounts for the users in the default “TreyUsers.csv” source file
.Example
Create-TreyUsers -Path “C:\temp\NewUsers.txt”
Creates AD accounts for the users listed in the file C:\temp\NewUsers.txt”
.Parameter Path
The path to the input CSV file. The default value is “.\TreyUsers.csv”.
.Inputs
[string]
.Notes
    Author: Charlie Russel
 Copyright: 2015 by Charlie Russel
          : Permission to use is granted but attribution is appreciated
   Initial: 3/26/2015 (cpr)
   ModHist:
          :
#>
[CmdletBinding()]
Param(
     [Parameter(Mandatory=$False,Position=0)]
     [string]
     $Path = “.\TreyUsers.csv”
     )

$TreyUsers = @()
If (Test-Path $Path ) {
   $TreyUsers = Import-CSV $Path
} else {
   Throw  “This script requires a CSV file with user names and properties.”
}

ForEach ($user in $TreyUsers ) {
   New-AdUser -DisplayName $User.DisplayName `
              -GivenName $user.GivenName `
              -Name $User.Name `
              -SurName $User.SurName `
              -SAMAccountName $User.SAMAccountName `
              -Enabled $True `
              -PasswordNeverExpires $true `
              -UserPrincipalName $user.SAMAccountName `
              -AccountPassword (ConvertTo-SecureString -AsPlainText -Force -String 
“P@ssw0rd!” )
   If ($User.SAMAccountName -eq “Charlie” ) {
      $cprpwd = Read-Host -Prompt 'Enter Password for account: Charlie’ -AsSecureString
      Set-ADAccountPassword -Identity Charlie -NewPassword $cprpwd -Reset
      $SuperUserGroups = @()
      $SuperUserGroups = (Get-ADUser -Identity “Administrator” -Properties * ).MemberOf

      ForEach ($Group in $SuperUserGroups ) {
         Add-ADGroupMember -Identity $Group -Members “Charlie”
      }
      Write-Host “The user $user.SAMAccountName has been added to the following AD 
Groups: “
      (Get-ADUser -Identity $user.SAMAccountName -Properties * ).MemberOf
   }
}

When we run the Create-TreyUsers script, we get output only about the superuser account that was created, as shown in Figure 3-2.

Figure 3-2

Figure 3-2 Creating multiple AD DS users from a CSV file

If you want more detail about the individual accounts that you created, modify the New-ADUser command in the script to include the PassThru parameter. With that change, though, you’ll get a lot more detail than you likely want. Instead, try a quick one-line search to find the users.

(Get-ADUser -Filter {Enabled -eq “True”} -Properties DisplayName).DisplayName
Dave R. Guy
Alfie NoNose
Stanley T. Behr
Dame Priscilla
Harold S. Catz
Sir William Wallace
Lord Barksalot
Charlie Russel

Now that’s just introduced a whole new set of issues with the Filter parameter. I’ll cover filters, both traditional Windows PowerShell filters as we used here and LDAP filters, later in the “Manage groups” section, but for the moment let’s examine this particular one-line search. The goal of the search is to get a list of the users we just created. Get-ADUser is the cmdlet to use to get users, but we only want to get a list of users that are actually enabled, to avoid accounts like the Guest account and some other special accounts. To get the DisplayName value, we need to add that property to the list of properties returned by Get-ADUser because it isn’t part of the default properties.