DEV Community

Excalibra
Excalibra

Posted on

A Simple Script for Exporting Domain Accounts (Requires Regex)

Introduction:

A straightforward script for exporting domain accounts.

https://github.com/Excalibra/scripts/blob/main/d-pwsh-dc/Domain%20Users%20Export.ps1

If the company needs to verify the total number of personnel who are involved in production (production staff) monthly, the domain accounts of relevant production staff are exported. This allows the company to verify and cross-check the number of production staff with HR records, ensuring accurate reporting and management oversight. Essentially, it helps in maintaining an up-to-date and accurate count of employees directly involved in production activities.

Implementation:

Export specified organizational units for summary statistics, excluding system-built users.

# Export file path
$outputFile = "C:\Users\Administrator\Desktop\DomainUsersList.txt"

# Clear or create the export file
Out-File -FilePath $outputFile # -Encoding UTF8 -Force

# Import Active Directory module
Import-Module ActiveDirectory

# Set DistinguishedName for organizational units
$ous = @(
    "OU=Production Team,DC=CSXZX,DC=com",
    "OU=Training,DC=CSXZX,DC=com",
    "OU=Temporary Permissions,DC=CSXZX,DC=com"
)

foreach ($ou in $ous) {
    # Get all users in the organizational unit
    $users = Get-ADUser -Filter * -SearchBase $ou -Properties Name

    # Write user names to the file
    if ($users) {
        $ouName = (Get-ADOrganizationalUnit -Identity $ou).Name  # Get OU name
        Add-Content -Path $outputFile -Value "Organizational Unit: $ouName"
        foreach ($user in $users) {
            Add-Content -Path $outputFile -Value $user.Name  # Keep only user names
        }
        Add-Content -Path $outputFile -Value "`r`n"  # Add line separator
    } else {
        Write-Host "No users found in the organizational unit $ouName."
    }
}

Write-Host "All user names from specified organizational units have been exported to $outputFile"

# Pause for 5 seconds
Start-Sleep -Seconds 5
Enter fullscreen mode Exit fullscreen mode

Then open VSCode and use regular expressions:

  • Match all lines with "Organizational Unit" and subsequent characters: ^.*Organizational Unit.*$
  • Match all lines with "Production" and subsequent characters: ^.*Production.*$
  • Match all lines with "Test" and subsequent characters: ^.*Test.*$
  • Remove all blank lines: ^\s*\n

Top comments (0)