This guide demonstrates a PowerShell script to query Active Directory for users, filter them by a specific pattern, extract relevant information, and then export the results to a CSV file. This is particularly useful for auditing or reporting purposes.
PowerShell Script to Get Filtered AD Users
The following script connects to your Active Directory domain, filters user accounts starting with “PS”, extracts their account number (trailing digits from SamAccountName), account name, first name, and last name, and then outputs the results to both the console and a CSV file.
Before running, ensure you have the ActiveDirectory module installed and that you have appropriate permissions to query your domain.
# Import the Active Directory module
Import-Module ActiveDirectory
# Define the domain and search base
$domain = "mydomain.com"
$searchBase = "CN=Users,DC=mydomain,DC=com"
# Query AD for users starting with "PS*"
try {
$users = Get-ADUser -Filter 'SamAccountName -like "PS*"' -SearchBase $searchBase -Properties GivenName, Surname -Server $domain
# Check if any users were found
if ($users.Count -eq 0) {
Write-Host "No accounts starting with 'PS*' found in $searchBase"
exit
}
# Process users and extract trailing digits from SamAccountName
$results = $users | Select-Object @{
Name = 'account#'
Expression = {
if ($_.SamAccountName -match '^PS.*(\d+)$') {
$matches[1] # Extract trailing digits after PS or PSS
} else {
"N/A" # Return 'N/A' if no trailing digits
}
}
}, @{
Name = 'account'
Expression = {$_.SamAccountName}
}, @{
Name = 'firstName'
Expression = {$_.GivenName}
}, @{
Name = 'lastName'
Expression = {$_.Surname}
} | Sort-Object -Property 'account#'
# Output results in a formatted table
$results | Format-Table -AutoSize
# Export to CSV
$results | Export-Csv -Path "ADUsers_PS_Digits.csv" -NoTypeInformation
Write-Host "Results exported to ADUsers_PS_Digits.csv"
}
catch {
Write-Error "Error querying Active Directory: $_"
}
Script Explanation
Let’s break down how this PowerShell script works step-by-step:
-
Import-Module ActiveDirectory: This line loads the Active Directory module, which provides the necessary cmdlets (commands) to interact with AD. Without this,Get-ADUserand other AD-related commands would not be recognized. -
$domain = "mydomain.com"and$searchBase = "CN=Users,DC=mydomain,DC=com": These lines define variables for your Active Directory domain and the specific organizational unit (OU) or container where you want to search for users. You should modify these values to match your environment. -
try { ... } catch { ... }: The script uses atry-catchblock for error handling. This ensures that if an error occurs during the Active Directory query (e.g., domain controller is unreachable, insufficient permissions), the script will gracefully catch the error and display a message instead of crashing. -
$users = Get-ADUser -Filter 'SamAccountName -like "PS*"' -SearchBase $searchBase -Properties GivenName, Surname -Server $domain: This is the core command for querying Active Directory:Get-ADUser: The cmdlet used to retrieve user objects from Active Directory.-Filter 'SamAccountName -like "PS*"': This filters the results to include only user accounts where theSamAccountName(the pre-Windows 2000 logon name) starts with “PS”. You can modify this filter to match other patterns (e.g.,'Enabled -eq $true'for active users).-SearchBase $searchBase: Specifies the starting point for the search in Active Directory.-Properties GivenName, Surname: By default,Get-ADUserreturns a limited set of properties. This parameter explicitly requests additional properties likeGivenName(first name) andSurname(last name).-Server $domain: Specifies the domain controller to query.
-
if ($users.Count -eq 0) { ... }: This checks if theGet-ADUsercommand returned any users. If no users match the filter, it prints a message and exits the script. -
$results = $users | Select-Object ... | Sort-Object -Property 'account#': This section processes the retrieved user objects:Select-Object: This cmdlet is used to create custom objects with specific properties.@{ Name = 'account#'; Expression = { if ($_.SamAccountName -match '^PS.*(\d+)$') { $matches[1] } else { "N/A" } } }: This is a calculated property. It creates a new property namedaccount#. TheExpressionuses a regular expression (-match '^PS.*(\d+)$') to findSamAccountNamevalues that start with “PS” followed by any characters and then one or more digits at the end. If a match is found, it extracts these trailing digits ($matches[1]). Otherwise, it assigns “N/A”.@{ Name = 'account'; Expression = {$_.SamAccountName} }: Creates anaccountproperty with the user’sSamAccountName.@{ Name = 'firstName'; Expression = {$_.GivenName} }: Creates afirstNameproperty with the user’sGivenName.@{ Name = 'lastName'; Expression = {$_.Surname} }: Creates alastNameproperty with the user’sSurname.Sort-Object -Property 'account#': Sorts the resulting objects based on theaccount#property.
-
$results | Format-Table -AutoSize: This line takes the$resultsobjects and displays them in a formatted table in the PowerShell console.-AutoSizeadjusts column widths for readability. -
$results | Export-Csv -Path "ADUsers_PS_Digits.csv" -NoTypeInformation: This exports the$resultsobjects to a CSV file:Export-Csv: The cmdlet used to convert objects into a series of comma-separated value (CSV) strings and save them to a file.-Path "ADUsers_PS_Digits.csv": Specifies the name and location of the output CSV file.-NoTypeInformation: Prevents PowerShell from including a type information header in the first line of the CSV file, which is usually not desired for data files.
-
Write-Host "Results exported to ADUsers_PS_Digits.csv": Informs the user that the CSV export was successful. -
Write-Error "Error querying Active Directory: $_": If an error occurs within thetryblock, this line in thecatchblock will display a detailed error message.
Example Output
Assuming you have AD users like PS1001, PS1002, PS1003, PS1004, PS1005 with corresponding first and last names, the console output would look similar to this:
account# account firstName lastName
-------- ------- --------- --------
1001 PS1001 John Doe
1002 PS1002 Jane Smith
1003 PS1003 Peter Jones
1004 PS1004 Alice Williams
1005 PS1005 Bob Brown
Example CSV Output (ADUsers_PS_Digits.csv)
The generated ADUsers_PS_Digits.csv file would contain:
"account#","account","firstName","lastName"
"1001","PS1001","John","Doe"
"1002","PS1002","Jane","Smith"
"1003","PS1003","Peter","Jones"
"1004","PS1004","Alice","Williams"
"1005","PS1005","Bob","Brown"
How to Use the Script
- Save the script: Save the code above as a
.ps1file (e.g.,Get-ADUsers.ps1). - Modify Domain Information: Update the
$domainand$searchBasevariables to match your Active Directory environment. - Make the script executable (Optional, but recommended for easier execution):
Open PowerShell as an administrator and run:
This allows local scripts to run without requiring a digital signature.
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser - Run the script: Navigate to the directory where you saved the script in PowerShell and execute it:
Ensure you have appropriate Active Directory permissions to query your domain.
.\Get-ADUsers.ps1