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:

  1. Import-Module ActiveDirectory: This line loads the Active Directory module, which provides the necessary cmdlets (commands) to interact with AD. Without this, Get-ADUser and other AD-related commands would not be recognized.

  2. $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.

  3. try { ... } catch { ... }: The script uses a try-catch block 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.

  4. $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 the SamAccountName (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-ADUser returns a limited set of properties. This parameter explicitly requests additional properties like GivenName (first name) and Surname (last name).
    • -Server $domain: Specifies the domain controller to query.
  5. if ($users.Count -eq 0) { ... }: This checks if the Get-ADUser command returned any users. If no users match the filter, it prints a message and exits the script.

  6. $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 named account#. The Expression uses a regular expression (-match '^PS.*(\d+)$') to find SamAccountName values 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 an account property with the user’s SamAccountName.
    • @{ Name = 'firstName'; Expression = {$_.GivenName} }: Creates a firstName property with the user’s GivenName.
    • @{ Name = 'lastName'; Expression = {$_.Surname} }: Creates a lastName property with the user’s Surname.
    • Sort-Object -Property 'account#': Sorts the resulting objects based on the account# property.
  7. $results | Format-Table -AutoSize: This line takes the $results objects and displays them in a formatted table in the PowerShell console. -AutoSize adjusts column widths for readability.

  8. $results | Export-Csv -Path "ADUsers_PS_Digits.csv" -NoTypeInformation: This exports the $results objects 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.
  9. Write-Host "Results exported to ADUsers_PS_Digits.csv": Informs the user that the CSV export was successful.

  10. Write-Error "Error querying Active Directory: $_": If an error occurs within the try block, this line in the catch block 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

  1. Save the script: Save the code above as a .ps1 file (e.g., Get-ADUsers.ps1).
  2. Modify Domain Information: Update the $domain and $searchBase variables to match your Active Directory environment.
  3. Make the script executable (Optional, but recommended for easier execution): Open PowerShell as an administrator and run:
    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
    
    This allows local scripts to run without requiring a digital signature.
  4. Run the script: Navigate to the directory where you saved the script in PowerShell and execute it:
    .\Get-ADUsers.ps1
    
    Ensure you have appropriate Active Directory permissions to query your domain.