The Get-ADUser PowerShell cmdlet allows you to get information about an Active Directory user, its attributes, and search among domain users. It is one of the more popular PowerShell cmdlets for getting information from AD. Using the Get-ADUser cmdlet, you can get the value of any attribute of an AD user account, list domain users with attributes, export user reports to CSV files, and use various criteria to select and filter domain users.
- Get-ADUser Cmdlet in Active Directory PowerShell Module
- How to Find AD User and List Properties with Get-ADUser?
- Get-ADUser -SearchBase: Getting Users from Specific OUs
- How to Get a User’s Email Address from AD Using PowerShell?
- Get-ADUser: Exporting Active Directory Users to CSV with PowerShell
- Get-ADUser Filter Examples
- PowerShell Get-ADUser Examples
Get-ADUser Cmdlet in Active Directory PowerShell Module
The Get-ADUser
cmdlet is included in a special module for interacting with Active Directory – Active Directory Module for Windows PowerShell. The RSAT-AD-PowerShell module cmdlets enable you to perform various operations on AD objects.
In this example, we’ll show how to use the Get-ADUser PowerShell cmdlet to get information about the last time a user’s password was changed, when the password expires, and other users’ properties.
To use the RSAT-AD-PowerShell module, you need to run the elevated PowerShell console and import the module with the command:
Import-Module ActiveDirectory
The RSAT-AD-PowerShell module is installed by default on Windows Server 2012 (and newer) when you deployed the Active Directory Domain Services (AD DS) role. To install the module on a domain member Windows Server host, run the command:
Install-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature
In order to use the Get-ADUser cmdlet on desktop Windows 10/11, you need to install the appropriate version of RSAT. You can enable RSAT through Settings -> Apps -> Optional Features -> Add a feature -> RSAT: Active Directory Domain Services and Lightweight Directory Services Tools.
You can install the RSAT AD module on Windows 10 and 11 with PowerShell:
Add-WindowsCapability –online –Name "Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0"
If the RSAT-AD-PowerShell module is not installed on the computer, then when you run the Get-ADUser command, an error will appear:
Get-ADUser: The term 'get-aduser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Check that the module is installed, and if necessary, import it into your PowerShell session:
Import-Module ActiveDirectory
Import-Module "C:\PS\AD\Microsoft.ActiveDirectory.Management.dll"
Import-Module "C:\PS\AD\Microsoft.ActiveDirectory.Management.resources.dll"
A complete list of all the arguments of the Get-ADUser cmdlet can be obtained as follows:
help Get-ADUser
How to Find AD User and List Properties with Get-ADUser?
To display the list of all domain user accounts, run this command:
Get-ADUser -filter *
To display the properties of a specific user, use the –Identity
parameter. Identity can be a username, login (SAMAccountName), DN (Distinguished Name), SID, or GUID.
The following PowerShell commands will return the same result for the same AD user account:
Get-ADUser –Identity b.smith
Get-ADUser –Identity "CN=Brian Smith,OU=Users,OU=Berlin,DC=woshub,DC=loc"
Get-ADUser –Identity "Brian Smith"
By default, the Get-ADUser cmdlet returns only 10 basic user attributes (out of more than 120 user account properties): DistinguishedName, SamAccountName, Name, SID, UserPrincipalName, ObjectClass, account status (Enabled: True/False according to the UserAccountControl AD attribute), etc. In this case, the cmdlet’s output doesn’t contain information about the time of the last user password change.
Get-ADUser –Server DC01.woshub.com –Identity tstuser
If you need to get user data from another AD domain, you need to specify the domain controller name and credentials to access it:
$ADcred = Get-Credential
Get-ADUSer tstuser -Server DC01.contoso.com -Credential $ADcred
To display the detailed information about all available user attributes, run this command:
Get-ADUser -identity tuser -properties *
The Get-ADUser cmdlet with the Properties * switch lists all the AD user’s attributes and their values (including empty ones). A similar list of user attributes is available in the Active Directory Users and Computers graphical snap-in (dsa.msc
) under the attribute editor tab.
Then we’ll go to the formatting of Get-ADUser output so that the necessary user attributes are displayed. For example, you want to display the values of the following user properties:
- PasswordExpired
- PasswordLastSet
- PasswordNeverExpires
- LastLogonTimestamp
Run the command:
Get-ADUser tuser -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires, lastlogontimestamp
Now in the user data, there is the information about the account password status (Expired: True/False), the date of the last password changes, and the time of the last user logon to the domain (lastlogontimestamp
attribute). To display this information in a more convenient table view and remove all unnecessary attributes use the Select-Object –Property and Format-Table:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Get-ADUser -SearchBase: Getting Users from Specific OUs
To display users only from a specific domain container (Organizational Unit), use the –SearchBase parameter:
Get-ADUser -SearchBase 'OU=London,DC=woshub,DC=loc' -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
If you need to select users from multiple OUs at once, use the following PowerShell script:
$OUs = "OU=NY,DC=woshub,DC=com","OU=LA,DC=woshub,DC=com","OU=MA,DC=woshub,DC=com"
$OUs | foreach {Get-ADUser -SearchBase $_ -Filter * |select Name, Enabled}
How to Get a User’s Email Address from AD Using PowerShell?
User email address is one of the user object attributes in Active Directory. To list the email addresses of users, you must add the EmailAddress field to the properties of the Get-ADUser cmdlet.
Get-ADUser -filter * -properties EmailAddress -SearchBase 'OU=Paris,OU-Fr,DC=woshub,DC=com'| select-object Name, EmailAddress
The list of enabled user accounts with e-mail addresses:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Format-Table
To get the list of Active Directory users with no Email address:
Get-ADUser -Filter * -Properties EmailAddress | where -Property EmailAddress -eq $null
The following example allows you to export a company email list from AD to a CSV file. Later, you can import this CSV address list into desktop email clients such as Outlook or Mozilla Thunderbird:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Export-Csv -NoTypeInformation -Encoding utf8 -delimiter "," $env:temp\adress_list.csv
Get-ADUser: Exporting Active Directory Users to CSV with PowerShell
The resulting list of domain users with attributes can be exported to a text file:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires > C:\temp\users.txt
Or you can export the AD users list to a CSV file:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | where {$_.name –like "*Dmitry*"} | sort-object PasswordLastSet | select-object Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires | Export-csv -path c:\tmp\user-passwords-expires.csv -Append -Encoding UTF8
Get-ADUser Filter Examples
Using the –Filter switch, you can filter the list of user accounts by one or more attributes. This is useful for searching AD users whose attributes match specified criteria. Values for specific attributes of Active Directory users can be specified as arguments to this parameter. When you use the –Filter
parameter, the Get-ADUser cmdlet will only display users that match the filter criteria.
For example, I want to list active (Enabled) user accounts whose name contains “Dmitry”. The example below uses multiple filters; you can combine conditions using the logical PowerShell comparison operators. In this example, user attributes must satisfy both filter conditions (-and):
Get-AdUser -Filter "(Name -like '*Dmitry*') -and (Enabled -eq 'True')" -Properties * |select name,enabled
All PowerShell logical operators can be used to select values for user attributes (-eq
, -ne
, -gt
, -ge
, -lt
, -le
, -like
, -notlike
, -and
, -or
, etc.)
Additionally, you can sort the resulting list of users by a specific user attribute with the Sort-Object cmdlet. You can also use the Where-Object cmdlet to specify multiple filtering criteria at once.
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires -SearchBase 'OU=NY,DC=woshub,DC=com'| where {$_.name –like "*Dmitry*" -and $_.Enabled -eq $true} | sort-object PasswordLastSet | select-object Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Thus, you can get a list of users with any necessary Active Directory attributes.
To search for users by several attributes at once (legacyExchangeDN, proxyAddresses, SAMAccountName, Surname, DisplayName, SamAccountName, physicalDeliveryOfficeName, RDN, and msExchMailNickname), you can use the Ambiguous Name Resolution (ANR
) feature:
Get-ADUser -Filter {anr -eq 'John'} | select Name
You can use an LDAP filter in Get-ADUser queries. An LDAP filter is specified using the –LdapFilter attribute.
Get-ADUser -LDAPFilter '(&(department=it)(title=sysops))'
PowerShell Get-ADUser Examples
Let’s show some more useful PowerShell command examples for querying Active Directory users with various filters. You can combine them to get the required list of AD user objects:
Display AD users, whose name starts with Joe:
Get-ADUser -filter {name -like "Joe*"}
You can use PowerShell to calculate the total number of user accounts in the Active Directory:
Get-ADUser -Filter {SamAccountName -like "*"} | Measure-Object
Find disabled Active Directory user accounts:
Get-ADUser -Filter {Enabled -eq "False"} | Select-Object SamAccountName,Name,Surname,GivenName | Format-Table
You can check the Active Directory user account creation date with the command:
get-aduser -Filter * -Properties Name, WhenCreated | Select name, whenCreated
You can get the list of newly added Active Directory users created in the last 24 hours:
$lastday = ((Get-Date).AddDays(-1))
Get-ADUser -filter {(whencreated -ge $lastday)}
List the accounts with an expired password (you can configure password expiration options in the domain password policy):
Get-ADUser -filter {Enabled -eq $True} -properties name,passwordExpired| where {$_.PasswordExpired}|select name,passwordexpired
Task: for the list of user accounts that are stored in a text file (one account per line), you need to get the user’s company name from AD and save it to a CSV file (you can easily import this CSV file into Excel).
Import-Csv c:\ps\users_list.csv | ForEach {
Get-ADUser -identity $_.user -Properties Name, Company |
Select Name, Company |
Export-CSV c:\ps\users_ad_list.csv -Append -Encoding UTF8
}
The users who haven’t changed their domain passwords in the last 90 days:
$90_Days = (Get-Date).adddays(-90)
Get-ADUser -filter {(passwordlastset -le $90_days)}
Find inactive user accounts (not logged on to the domain for more than 180 days). The lastLogonTimestamp attribute is used to get the user’s logon history to the domain:
$LastLogonDate= (Get-Date).AddDays(-180)
Get-ADUser -Properties LastLogonTimeStamp -Filter {LastLogonTimeStamp -lt $LastLogonDate } | ?{$_.Enabled –eq $True} | Sort LastLogonTimeStamp| FT Name, @{N='lastlogontimestamp'; E={[DateTime]::FromFileTime($_.lastlogontimestamp)}} -AutoSize
To get a user’s photo from Active Directory and save it to a jpg file, run the following commands:
$usr = Get-ADUser sjoe -Properties thumbnailPhoto
$usr.thumbnailPhoto | Set-Content sjoe.jpg -Encoding byte
To get a list of AD groups which the user account is a member of:
Get-AdUser sjoe -Properties memberof | Select memberof -expandproperty memberof
List the users from the OU that are members of a specific domain security group:
Get-ADUser -SearchBase 'OU=Rome,OU=Italy,DC=woshub,DC=com' -Filter * -properties memberof | Where-Object {($_.memberof -like "*CEO*")}
List users from the OU that are members of a specific domain security group:
Get-ADUser -SearchBase 'OU=Rome,OU=Italy,DC=woshub,DC=com' -Filter * -properties memberof | Where-Object {($_.memberof -like "*CEO*")}
List all users from the OU, except for members of a specific group:
$Users = Get-ADUser -filter * -SearchBase ‘OU=Berlin,DC=woshub,DC=com’ -properties memberOf
ForEach ($User In $Users)
{
$Groups = -join @($User.memberOf)
If ($Groups -notlike '*Domain Admins*')
{
$User.Name
}
}
Exporting a list of AD users with the Organizational Unit name to the Out-GridView table:
get-aduser -filter * -Properties cn,canonicalname | select name,userprincipalname,@{Name="OU";expression={$_.Canonicalname.substring(0,$_.canonicalname.length-$_.cn.length)}}| Out-GridView
Check that the AD user account exists:
$SamAccountName='jbrown'
if (@(Get-ADUser -Filter { SamAccountName -eq $SamAccountName }).Count -eq 0)
{ Write-Host "User $SamAccountName doesn’t exist"}
List the domain computers the user is allowed to sign in (logon restriction through the LogonWorkstations AD attribute).
Get-ADUser jbrown -Properties LogonWorkstations | Format-List Name, LogonWorkstations
30 comments
Thanks for this useful information. I’m trying the following script, it works fine on powershell, but when i try to export it to csv, its not readable text in it. Some strings are there only.
PS C:\> Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
PS C:\> Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires | Export-Csv -Path c:\temp\password-change.csv
Please help.
You can use:
PS C:\> Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires > c:\temp\password-change.csv
So I need to get some info for our auditors and have little time to do so. Certain properties they want need a False or True output and I don’t know how to do that. Here is my command which did not work with the properties that needed a true or false output:
Get-ADUser -Filter * -Properties * | Select-Object samaccountname, isPreAuthNotRequired, isActive, isPwdEncryptedTextAllowed, displayname, isPwdNotRequired, userprincipalname, isDisabled, isExpired, distinguishedname | export-csv -path c:\export\allusers.csv
The objects like samaccountname came out fine; it’s just the ones that needed that true or false output. Please advise.
You are using non-existent AD attributes: isPreAuthNotRequired, isActive, isPwdEncryptedTextAllowed, isPwdNotRequired, isDisabled, isExpired
The state of an AD account is described using the UserAccountControl bit mask attribute. Each bit of the attribute is a separate flag (enabled or disabled)
In this article, there is a small Powerhell script that allows you to get information from the UserAccountControl attribute in a simple way. https://woshub.com/decoding-ad-useraccountcontrol-value/
Very good information thanks
you are using ft Name, you have to use Select statement for same object properties.
I want to combine two of these reports into one, but I don’t know how to format the command:
Using the “List all active AD accounts”, I want to add password info (password last set, password expired, passwordneverexpires flag set) so I get a list of active AD accounts, logon name, user name and password info.
You can use the following query:
Get-ADUser -Filter {Enabled -eq “True”} -properties name,SamAccountName,PasswordExpired, PasswordLastSet, PasswordNeverExpires| Select-Object name,SamAccountName,PasswordExpired, PasswordLastSet, PasswordNeverExpires | Format-Table
Thanks. With a little tweaking I can now show the columns in the order I want and sort the list by name (actually any column I choose), and I can even export the results. Still a lot to learn but this site is a great resource.
i have a csv file contain company attribute for a large number about 2000 users i want to get the domain users login accounts for these users exported in csv file that contain the login users and the company filed for etch user in the csv file
Suppose you have a file userlist.csv that contain a list of users in the following format:
SamAccountName
user1
user2
user3
user4
And run this script:
Import-Csv C:\Ps\userlist.csv | ForEach {
Get-ADUser -Identity $_.SamAccountName -properties samaccountname,company | `
select samaccountname,company | `
Export-CSV C:\ps\output.csv -notype -encoding UTF8 -Append
}
Hi- I am sure script is fine but not sure why am i getting error below.
Get-ADUser : Cannot validate argument on parameter ‘Identity’. The argument is null or an element of the argument
collection contains a null value.
At line:2 char:22
+ Get-ADUser -Identity $_.SamAccountName -properties samaccountname,com …
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
thank you very much for this awesome information.
and lots of samples!
helped me a lot!
i want to export my domain user details with following column
username / login id / mail id / description / manager name
please share the script
Get-ADUser -filter * -properties displayName, sAMAccountName, mail,description, manager| ft displayName, sAMAccountName, mail,description, manager | Export-csv -path c:\ps\adusers.csv
I want to export ad users which is not used from last 365 days. And after that wants to delete the same.
so pleas share the script separately of both queries.
You can filter active users using LastLogon attribute. To export this list to a CSV file, use Export-CSV cmdlet:
$IncativeDays = (Get-Date).adddays(-365)
Get-ADUser -Filter {LastLogon -lt $IncativeDays -and enabled -eq $true} -properties displayName, company, LastLogon | select-object displayName, company,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}} | Export-CSV c:\ps\users_ad_list.csv -Append -Encoding UTF8
To delete these Active Directory user accounts, you can use pipe to Remove-ADUser
Get-ADUser -Filter {LastLogon -lt $IncativeDays -and enabled -eq $true} -properties displayName, company, LastLogon | Remove-ADUser
how do you get-user -filter {name -like “name*”} | select-object samaccount,name,surname, | format-table but also include the -member of and search for a particular group and see if he has it in their member of. I have their first and last name and want to cut the the time by looking up their username, therefore I have first and last name but last name will suffice
Hello
I am looking to fetch all the user details from AD for the below columns and export it to .csv file.
Please help
First Name
Last Name
User Created Date
Type – Group / User
Role
Last password Change
Las Modified Date
Description
Thanks In Advance
#Powershell script to fetch AD user details including AD Group membership into csv.
# Input file is a csv with list of samaccountnames and header as ‘samaccountname’
#BEGIN SCRIPT
Import-Module ActiveDirectory
$usersList = Import-Csv -Path C:\Temp\samaccountname_usersIN.csv
# Loop through CSV and get users if the exist in CVS file
foreach ($user in $usersList) {
$SamAccountName = $user.SamAccountName
Get-ADUser -Filter {SamAccountName -like $SamAccountName} -Properties * | Select-Object UserPrincipalName,EmailAddress,mail,SamAccountName,@{“name”=”MemberOf”;”expression”={$_.MemberOf}},Street,CanonicalName,DistinguishedName,@{“name”=”proxyaddresses”;”expression”={$_.proxyaddresses}},Name,GivenName,Surname,DisplayName,LastLogonDate,Enabled,EmployeeID | export-csv -Append C:\Temp\UserDetails_Out.csv -noType
}
#END SCRIPT
How can we fetch report of members in each group of specific OU with timestamp?
I am getting timeout error upon connecting to other server, how can I overcome this problem?
I am looking for a powershell command that can help me with all the enabled users in my AD from all the OU’s with attributes namely EmployeeID, Employeenumber, email ID, managers name, department, job title, phone number, state, country, logon name.
Can anybody help me with this command.
i want to search two multiple samaccount like “srv.” and “service”
Its worked for single samaccount but not for double. Please help
Get-ADUser -Filter {anr -eq ‘srv.’} | select Name
I want to give an alias for a property name.
For instance,
Get-ADUser -Filter {name -like “*son*” | Properties Name, msDS-cloudExtensionAttribute1
How can I set an alias for msDS-cloudExtensionAttribute1 ?
Please suggest.
Get-ADUser -Filter {name -like “*son*”} -properties msDS-cloudExtensionAttribute1 | select Name, @{name='youralias';expression={$_.msDS-cloudExtensionAttribute1}}
Thank you for prompt reply.
Hello,
thanks for this really useful page! 🙂 I tried to modify a script but it works just for half columm:
$LastLogonDate= (Get-Date).AddDays(-180)
Get-ADUser -Properties LastLogonTimeStamp -Filter {LastLogonTimeStamp -lt $LastLogonDate } | ?{$_.Enabled –eq $True} | Sort LastLogonTimeStamp| FT Name, @{N=’lastlogontimestamp’; E={[DateTime]::FromFileTime($_.lastlogontimestamp) | Export-csv -path c:\AD\Reports\Inactive_users.csv -Append -Encoding UTF8}} -AutoSize
And I didn’t understand how to put it in multiple line by Visual Studio Code with PS extension…
I want script to get list of AD users modified with their modification date for past 9months. Please help me to get the same.
$date = ((get-date).addmonths(-9))
Get-ADUser -Filter * -Properties whenChanged| Where-Object {$_.whenChanged -ge $date} | select name