Active Directory (PowerShell)

From vWiki
Jump to navigation Jump to search

Getting Started

You need to have RSAT (Remote Server Administration Tools) installed For Windows 7 see - http://www.microsoft.com/en-gb/download/details.aspx?id=7887. This enables your local machine to remotely manage Windows Servers and Services via the usual MMC GUI's (eg AD Users and Computers) and (most importantly) includes PowerShell modules in order to be able to do so as well.

Be aware that PowerShell DFS management is currently poor, its only possible from Windows 8 and 2012 machines, and even then its very limited.

Once installed go to Control Panel | Programs | Turn Windows features on or off and enable the PowerShell module, full path as follows...

  • Remote Server Administration Tools | Role Administration Tools | Active Directory Module for Windows PowerShell

In order to be able access the PowerShell Active Directory CmdLets, import the AD module into your PowerShell session...

Import-Module ActiveDirectory

Credentials

Whilst its probably possible to perform Get/read-only CmdLets from your normal login, you should need to use an admin account to actually make changes. If you get the following error, you probably need to supply different username and password credentials to the command.

  • Either the target name is incorrect or the server has rejected the client credentials.

All of the Active Directory module commands allow you to specify a -Credential, you can either pre-create a credentials object, or supply one at the time of running the command.

$cred = Get-Credential                                                        # Create a credential object, the command will ask for your user/pass
Add-ADGroupMember -Identity $Group -Members $Users -Credential $cred          # Add $users to $Group, using $cred credentials

# Alternatively do it all in the same command
Add-ADGroupMember -Identity $Group -Members $Users -Credential (Get-Credential)

For more info on using Credentials in PowerShell see this page - Credentials_(PowerShell)

Group Policy

The PowerShell GPO module is installed with

In order to be able access the PowerShell GPO CmdLets, import the GPO module into your PowerShell session...

Import-Module GroupPolicy

Users

AD Fields

Field names don't necessarily match up between the PowerShell module, LDAP, and what you see in the Users and Computers MMC GUI, see below for an in-exhaustive list...

Active Directory user field equivalents
PowerShell ldapDisplayName Users and Computers Comments
UserPrincipalName Account | User logon name
Name name Account | Pre Win2k login name
GivenName givenName General | First name
Surname sn General | Last name
DisplayName displayName General | Display Name
Description description General | Description
Path N/A N/A X.500 path of OU/container for object
SamAccountName sAMAccountName Set to same as name if not specified
AccountPassword If not set, new user account is disabled

Get-ADUser examples

$users = Get-ADUser -Filter * -SearchBase "DC=domain,DC=com"                           # Get all users in domain.com
$user = Get-ADUser -Filter {SamAccountName -eq "username"}                             # Get user by logon/SAM account name
$user = Get-ADUser -Filter {SamAccountName -eq "username"} -Properties *               # Get all properties for user
$user = Get-ADUser -Filter {{Surname -eq "last" -and GivenName -eq "first"}}           # Get user by first and last names
$users = Get-ADUser -Filter * -SearchBase "OU=London,OU=Users,DC=EU,DC=domain,DC=com"  # Get users in London OU

To create a CSV export of fields from AD...

$users = Get-ADUser -Filter * -SearchBase "DC=DOMAIN,DC=COM" -Properties Enabled, CanonicalName, Country, Created, LastLogonDate, mail
$users | Select-Object Name, Enabled, CanonicalName, Country, Created, LastLogonDate, mail | export-csv -Path users.csv
  • LastLogonDate - Be aware that the last logon date field typically has an accuracy/tolerance of 14 days, AD intentionally doesn't update the field at every logon from the user/device object so as to reduce the amount of data replication between domain controllers

Distinguished Name

You can't filter using wildcards for the Distinguished Name filed (see http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/e6f5a98d-62d1-4659-b328-ebab6f546cc4).

As a workaround, do a generic export from AD and pipe it through a Where-Object CmdLet (not that if you have a large number of users in AD this isn't particularly efficient).

$users = Get-ADUser -Filter * | Where-Object {$_.DistinguishedName -like "*,CN=OuFolder,*"}

New-ADUser examples

# Create default new users password
$UsrPwd = ConvertTo-SecureString -String $BssUsrPassword -AsPlainText -Force

# Destination OU for new user
$DstPath = "OU=department,DC=domain,DC=com"

# Create new user
$Usr = New-ADUser -Name $LogonName -GivenName $firstname -Surname $lastname -Description $desc -AccountPassword $UsrPwd -ChangePasswordAtLogon $true -Path $DstPath  -PassThru

# Make user account active 
Set-ADUser $Usr -ChangePasswordAtLogon $true -Enabled $true

Remove-ADUser examples

It would normally be quite foolhardy to delete a user account that wasn't already disabled. Deletion removes group memberships, file-permissions etc etc. Whilst you can create a new account with the same name, it won't have the same SID so it's not the same account.

Remove-ADUser -Identity $user -Confirm:$false                   # $user retrieved from Get-ADUser, -Confirm:$false prevents confirmation prompt

Groups

Get-ADGroups examples

$group = Get-ADGroup "Operations Supervisors"                                                             # Get the "Operations Supervisors" group
$groups = Get-ADGroup -Filter 'Name -like "*Operations*"'                                                 # Get all security groups with Operations in the title
$groups = Get-ADGroup -Filter 'GroupCategory -eq "Security"' -SearchBase "OU=Groups,DC=DOMAIN,DC=COM"     # Get all security groups in the Groups OU

Copy Users From Existing Group

The script below copies users from an existing group and adds them to another group (existing users in the group are unaffected).

$Src_Group = "Source Group Name"
$Dst_Group = "Destination Group Name"
$Users = Get-ADGroupMember $Src_Group
Add-ADGroupMember -Identity $Dst_Group -Members $Users -Credential (Get-Credential)

AD Fields

Active Directory group field equivalents
PowerShell ldapDisplayName Users and Computers Comments
Name name General (name at top)
SamAccountName sAMAccountName General | Group name (per-Windows 2000) Set to same as name if not specified
N/A info General | Notes
Description description General | Description
Path N/A N/A X.500 path of OU/container for object

Computers

To disable a computer account, use Disable-ADAccoun

Get-ADComputer examples

$devices = Get-ADComputer -Filter * -SearchBase "DC=domain,DC=com" -Properties IPv4Address, OperatingSystem,  Created, LastLogonDate
  • LastLogonDate - Be aware that the last logon date field typically has an accuracy/tolerance of 14 days, AD intentionally doesn't update the field at every logon from the user/device object so as to reduce the amount of data replication between domain controllers

Remove-ADComputer examples

Remove-ADComputer -Identity $computer -Confirm:$false

Organisation Unit

New-ADOrganizationalUnit examples

$OU = New-ADOrganizationalUnit -Name "DeptX" -Path "DC=domain,DC=com" -PassThru

Errors

Managing Multiple Domains

Unless you've specified otherwise, commands will be handled by the domain identified by ...?

Use -Server and -Credentials options, available for all PowerShell AD commands, to specify the DC and credentials required to service the commands, for example...

$users = Get-ADUser -Filter * -SearchBase "DC=domain,DC=com"  -Server "10.10.1.10" -Credential $cred

For more info on working with credentials or help on creating a credentails object see Credentials_(PowerShell).