The Get-ADUser is the most commonly used PowerShell cmdlet for retrieving Active Directory user information, including attributes like usernames, email addresses, account activity, group memberships, contact details, job titles, organizational data, etc. Using the Get-ADUser cmdlet, you can get the value of any attribute of an AD user account, list domain users, export user reports to CSV/TXT files, and use various criteria to select and filter domain users.
dsquery
tool, and other tools. All of these tools can be easily replaced with the Get-ADUser cmdlet.Get-ADUser Cmdlet in the Active Directory PowerShell Module
To use the Get-ADUser
cmdlet to get information from AD, you must have the Active Directory module for PowerShell installed on the computer.
This module is installed on AD domain controllers along with the Active Directory Domain Services (AD DS) role. The AD module can also be installed manually on any computer (it is part of the RSAT package):
- Windows Server 2012 R2 and newer:
Install-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature
- Windows 11 and 10:
Get-WindowsCapability -Name RSAT.ActiveDirectory* -Online | Add-WindowsCapability -Online
Check that the module is installed, and if necessary, import it into your PowerShell session:
Get-Module ActiveDirectory
Import-Module ActiveDirectory
If RSAT-AD-PowerShell is not installed, you get an error when running the Get-ADUser command:
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.
Import-Module "C:\PS\AD\Microsoft.ActiveDirectory.Management.dll"
Import-Module "C:\PS\AD\Microsoft.ActiveDirectory.Management.resources.dll"
View the complete syntax and list of available arguments for the Get-ADUser cmdlet:
help Get-ADUser
How to Find AD User and List Properties with Get-ADUser
Let’s look at how to use the Get-ADUser cmdlet to find different information about domain users. The cmdlet can retrieve information for a single AD user or multiple users.
To display the list of all domain user accounts:
Get-ADUser -filter *
To get 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.
Lists the values of all available attributes for the specified user.
Get-ADUser -identity b.smith -properties *
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:
For example, I want to display information about whether a user’s password has expired (Expired: True/False), the last time the password was changed, when the user password expires, and the last time the user logged into the domain. This info is stored in the following user account attributes:
- PasswordExpired
- PasswordLastSet
- PasswordNeverExpires
- LastLogonTimestamp
Run the command:
Get-ADUser tuser -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires, lastlogontimestamp
To display only the specific user attributes in the output (remove all unnecessary attributes), filter them using Select-Object -Property or Format-Table. The following command displays the password status for all AD users in a convenient table view:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | Format-Table Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Get-ADUser –Server DC01.woshub.com –Identity tstuser
To retrieve user data from another Active Directory domain, specify the DC name and use the -Credential parameter to provide the access credentials:
$ADcred = Get-Credential
Get-ADUSer tstuser -Server DC01.contoso.com -Credential $ADcred
Get-ADUser -Filter Examples
The Get-ADUser -Filter parameter allows to filter the list of users by one or more attributes. This helps in finding Active Directory users whose attributes match specific criteria.
For example, I want to list active (Enabled) user accounts whose name contains “Dmitry”. To do this, a filter with multiple conditions is used. User attributes must meet both filter conditions in this example (-and).
Get-AdUser -Filter "(Name -like '*Dmitry*') -and (Enabled -eq 'True')" -Properties * |select name,enabled
To select values for user attributes, you can use all of the standard PowerShell logical comparison operators (-eq
, -ne
, -gt
, -ge
, -lt
, -le
, -like
, -notlike
, -and
, -or
, etc.)
You can use the Sort-Object cmdlet to sort the result list by a specific user property (attribute). In addition, you can use the Where-Object cmdlet to specify multiple filter 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
You can use LDAP filters in Get-ADUser queries. An LDAP filter can be specified by using the -LdapFilter attribute.
Get-ADUser -LDAPFilter '(&(department=it)(title=sysops))'
Exporting Active Directory Users to CSV/TXT Files with PowerShell
The Get-ADUser command can be used to output a list of domain users and their properties to a text file:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires > C:\temp\users.txt
Or, use the Export-CSV cmdlet to export users to a CSV file, that you can then easily open in Excel.
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
Export a company email address 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 Usage Examples
Let’s show several useful PowerShell command examples for querying Active Directory users with various filters. Combine them to get the list of AD user objects you need:
Display AD users, whose names begin with Joe:
Get-ADUser -filter {name -like "Joe*"}
Count the total number of user accounts in the Active Directory:
Get-ADUser -Filter {SamAccountName -like "*"} | Measure-Object
List disabled Active Directory users:
Get-ADUser -Filter {Enabled -eq "False"} | Select-Object SamAccountName,Name,Surname,GivenName | Format-Table
List AD user email addresses:
Get-ADUser -filter * -properties EmailAddress -SearchBase 'OU=Paris,OU-Fr,DC=woshub,DC=com'| select-object Name, EmailAddress
List enabled users and their email addresses:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Format-Table
Find the users who don’t have an Email address set:
Get-ADUser -Filter * -Properties EmailAddress | where -Property EmailAddress -eq $null
Get active users who don’t have a Department specified in their properties:
Get-AdUser -Filter "Enabled -eq 'True'" -Properties * |where Department -eq $null|select name,enabled, Department
Get the creation date of the Active Directory user account:
Get-ADuser -Filter * -Properties Name, WhenCreated | Select name, whenCreated
List users created in the last 24 hours:
$lastday = ((Get-Date).AddDays(-1))
Get-ADUser -filter {(whencreated -ge $lastday)}
List the accounts with expired passwords (password expiration options are set in the domain password policy):
Get-ADUser -filter {Enabled -eq $True} -properties name,passwordExpired| where {$_.PasswordExpired}|select name,passwordexpired
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 into the domain for more than 180 days). The LastLogonTimestamp attribute value is used to get the logon history of a domain user.
$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:
$usr = Get-ADUser sjoe -Properties thumbnailPhoto
$usr.thumbnailPhoto | Set-Content sjoe.jpg -Encoding byte
To get a list of 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
Select users from multiple OUs at once using the following PowerShell commands:
$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}
List the AD groups that 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 who 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*")}
Task: get the user’s company name from AD and save it to a CSV file for a list of user accounts in a text file (one account per line). You can then 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
}
List 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
}
}
Export a list of AD users with the Organizational Unit names (where they are located) 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 log on (logon restriction through the LogonWorkstations AD attribute).
Get-ADUser jbrown -Properties LogonWorkstations | Format-List Name, LogonWorkstations
33 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
I want to pull the report that has the Employee ID and ExtensionAttributes2 , Please advice.
Qual comando posso usar para verificar contas do AD com data de expiração?
What command can I use to check AD accounts with expiration date?
List all enabled AD accounts with the last password set and expiration date:
Get-ADUser -Filter (Enabled -eq "true") -Properties msDS-UserPasswordExpiryTimeComputed, PasswordLastSet, PasswordExpired |Select-Object -Property Name,PasswordLastSet, PasswordExpired,@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
How to extend an expired user password in AD