Jump to page sections
- Using Get-ADUser
- Targeting A Specific OU
- Get-ADUser Example With LastLogonTimestamp
- Using Get-ADObject And An LDAP Query
- Using ADSI and DirectorySearcher
- Code Example To Dump Every User In AD
- Targeting A Specific OU With ADSI/LDAP/DirectorySearcher
- Getting Accounts With An LDAP Query
- Getting Disabled AD Accounts
- Getting Enabled AD Accounts
- Using Get-QADUser
- Getting Every Single User From AD
- Getting Disabled AD Users
- Targeting A Specific OU With Get-QADUser
- Get-QADUser Example With LastLogonTimestamp
These MS AD cmdlets that Get-ADUser and Get-ADObject are part of are installed as a feature under the category "Remote Server Administration Tools" (RSAT) from Server Manager on Windows Server 2008 R2 and Windows 7. There's more information about this here and here. Also see Add-WindowsFeature and Get-WindowsFeature (use Get-Help).
See this article for getting computer names.Using Get-ADUser
PS C:\> Import-Module ActiveDirectory PS C:\>
Then you can simply use the filter "*" to target any user. Here I get the names of the last five users, using Select-Object to limit the results.
PS C:\> Get-ADUser -Filter '*' | Select -Exp Name -Last 5 hoppla testadmin deploymentuser SharePoint SharePointServices
Targeting A Specific OU
PS C:\> Get-ADUser -SearchBase 'OU=Bruker,DC=svendsen,DC=local' -Filter '*' | Select -Exp Name pwdnotusr1 pwdnotusr2 pwdnotusr3
Get-ADUser Example With LastLogonTimestamp
PS C:\> Get-ADUser -Filter '*' -Properties LastLogonTimestamp |
Sort LastLogonTimestamp |
Select Name,@{n='LastLogonTimestamp';e={if ($_.LastLogonTimestamp) { [datetime]::FromFileTime($_.LastLogonTimestamp)} } }
Name LastLogonTimestamp
---- ------------------
pwdnotusr3
pwdnotusr1
tullebruker
SharePointServices
deploymentuser
hoppla
krbtgt
Guest
SCCMuser 3/26/2011 2:04:12 PM
pwdnotusr2 9/25/2011 4:25:12 AM
testadmin 12/16/2011 3:10:29 PM
Administrator 3/3/2012 12:00:00 AM
SCOMuser 3/7/2012 1:15:40 AM
scomnotify 3/13/2012 3:25:16 AM
SharePoint 3/14/2012 1:15:34 AM
joakimbs 3/17/2012 7:14:01 AM
Using Get-ADObject And An LDAP Query
I describe this in more detail in the DirectorySearcher section, but basically this LDAP query filters out contacts and gets only "regular" user accounts.
PS C:\> Get-ADObject -LDAPFilter '(&(objectCategory=Person)(objectClass=User))' | Select -Exp Name -First 5 Guest krbtgt Administrator scomnotify SCOMuser
Using ADSI and DirectorySearcher
Using DirectoryServices.DirectorySearcher, you can have some logic in the LDAP query. To get users, you can use something like "objectCategory=User", but this will also get contacts. To get only "regular" user accounts, you can normally use "(&(objectCategory=Person)(objectClass=User))".
Also be aware that the properties you index from the returned System.DirectoryServices.ResultPropertyCollection object are case-sensitive. This almost tripped me up. All the properties appear to be all lowercase when you look at the object.Beware that this query is expensive if the AD is large.
Here's the first, simple example:PS C:\> $DirSearcher = [adsisearcher][adsi]''
PS C:\> $DirSearcher.Filter = '(&(objectCategory=Person)(objectClass=User))'
PS C:\> $DirSearcher.FindAll().GetEnumerator() | %{ $_.Properties.name } | ? { $_ -imatch '^scom' }
scomnotify
SCOMuser
I should also mention that there's a type accelerator in PowerShell (starting with v1, apparently), which allows you to skip a few steps like this (notice the two quotes after the type accelerator):
PS C:\> $DirSearcher = [adsisearcher]'' PS C:\>
You can also specify the filter directly, like this:
$Searcher = [ADSISearcher] "(SamAccountName=$something)"
if ($Searcher.FindOne().Count -eq 1) { "Found in AD" } else { "Not found in AD" }
Here's what the returned System.DirectoryServices.ResultPropertyCollection object looks like:
PS C:\> $DirSearcher.FindAll().GetEnumerator() | select -first 1 | %{ $_.Properties | gm }
TypeName: System.DirectoryServices.ResultPropertyCollection
Name MemberType Definition
---- ---------- ----------
Clear Method System.Void Clear()
Contains Method bool Contains(string propertyName)
CopyTo Method System.Void CopyTo(System.DirectoryServices.ResultPropertyValueCollection[] arra...
Equals Method bool Equals(System.Object obj)
GetEnumerator Method System.Collections.IDictionaryEnumerator GetEnumerator()
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Item ParameterizedProperty System.DirectoryServices.ResultPropertyValueCollection Item(string name) {get;}
Count Property System.Int32 Count {get;}
PropertyNames Property System.Collections.ICollection PropertyNames {get;}
Values Property System.Collections.ICollection Values {get;}
And these are the properties:
PS C:\> $DirSearcher.FindAll().GetEnumerator() | select -first 1 | %{ $_.Properties.PropertyNames }
iscriticalsystemobject
samaccountname
useraccountcontrol
primarygroupid
instancetype
objectclass
pwdlastset
memberof
samaccounttype
usnchanged
accountexpires
adspath
distinguishedname
codepage
name
whenchanged
dscorepropagationdata
description
countrycode
cn
whencreated
objectsid
objectguid
objectcategory
usncreated
Code Example To Dump Every User In AD
$DirSearcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ArgumentList ([adsi]'')
$DirSearcher.Filter = '(&(objectCategory=Person)(objectClass=User))'
$DirSearcher.FindAll().GetEnumerator() | ForEach-Object {
# These properties are part of a DirectoryServices.ResultPropertyCollection
# NB! These properties need to be all lowercase!
$_.Properties.name
}
Targeting A Specific OU With ADSI/LDAP/DirectorySearcher
$DirSearcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher `
-ArgumentList ([adsi]'LDAP://OU=Bruker,dc=svendsen,dc=local')
The relevant part is "[adsi]'LDAP://OU=Bruker,dc=svendsen,dc=local'". Here I target the OU svendsen.local/Bruker.
If you were to use the [adsisearcher] type accelerator, it would look like this:$DirSearcher = [adsisearcher][adsi]'LDAP://OU=Bruker,dc=svendsen,dc=local'
Getting Accounts With An LDAP Query
Getting Disabled AD Accounts
(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))
Putting it to use, we get:
PS C:\> $DirSearcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ArgumentList ([adsi]'')
PS C:\> $DirSearcher.Filter = '(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))'
PS C:\> $DirSearcher.FindAll().GetEnumerator() | %{ $_.Properties.name }
Guest
krbtgt
PS C:\>
Getting Enabled AD Accounts
(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))
This basically means "not disabled". The exclamation point, enclosed in parentheses in the LDAP query, negates the logic from the disabled user query - effectively retrieving users that are not disabled.
Putting it to use, we get:PS C:\> $DirSearcher = [adsisearcher][adsi]''
PS C:\> $DirSearcher.Filter = '(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))'
PS C:\> $DirSearcher.FindAll().GetEnumerator() | %{ $_.Properties.name }
Administrator
scomnotify
SCOMuser
joakimbs
SCCMuser
tullebruker
pwdnotusr1
pwdnotusr2
pwdnotusr3
hoppla
testadmin
deploymentuser
SharePoint
SharePointServices
PS C:\>
Using Get-QADUser
Firstly, you need to add the snap-in, unless you start Quest's separate shell:
PS C:\> Add-PSSnapin Quest.ActiveRoles.ADManagement PS C:\>
Getting Every Single User From AD
PS C:\> Get-QADUser -SizeLimit 0 | Select -Exp Name Guest krbtgt Administrator scomnotify SCOMuser joakimbs SCCMuser tullebruker pwdnotusr1 pwdnotusr2 pwdnotusr3 hoppla testadmin deploymentuser SharePoint SharePointServices PS C:\>
Getting Disabled AD Users
PS C:\> Get-QADUser -SizeLimit 0 -Disabled | Select -Exp Name Guest krbtgt PS C:\>
Targeting A Specific OU With Get-QADUser
PS C:\> Get-QADUser -SizeLimit 0 -SearchRoot svendsen.local/Bruker Name Type DN ---- ---- -- pwdnotusr1 user CN=pwdnotusr1,OU=Bruker,DC=svendsen,DC=local pwdnotusr2 user CN=pwdnotusr2,OU=Bruker,DC=svendsen,DC=local pwdnotusr3 user CN=pwdnotusr3,OU=Bruker,DC=svendsen,DC=local
Get-QADUser Example With LastLogonTimestamp
Here's an example where I include the LastLogonTimestamp property. Unlike with Get-ADUser from Microsoft, it's automatically converted to a human-readable date for you.
PS C:\> Get-QADUser -SizeLimit 0 -IncludedProperties LastLogonTimestamp | Select Name,LastLogonTimestamp Name LastLogonTimestamp ---- ------------------ Guest krbtgt Administrator 3/3/2012 12:00:00 AM scomnotify 3/13/2012 3:25:16 AM SCOMuser 3/7/2012 1:15:40 AM joakimbs 3/17/2012 7:14:01 AM SCCMuser 3/26/2011 2:04:12 PM tullebruker pwdnotusr1 pwdnotusr2 9/25/2011 4:25:12 AM pwdnotusr3 hoppla testadmin 12/16/2011 3:10:29 PM deploymentuser SharePoint 3/14/2012 1:15:34 AM SharePointServicesWindows Powershell AD
Blog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How Many Bitcoins (BTC) Are Lost
- How many people own 1 full BTC
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Silver - The Underrated Investment
- Simple Morningstar Fund Report Script
- Sølv - den undervurderte investeringen
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API