The script pulls a list of users from certain OU"s . It works great but we have some OU’s under the main OU that I need to exclued
Main OU will always be the $ou in the script.
The OU"s that I will need to exclude are
$ou Service Accounts
$ou Super Accounts
Disabled Users
This is all under the main OU
Main OU <~ this name changes based on main OU in our enviroment
Example
Azure
Azure Users
Azure Seasonal Accounts
Azure Service Accounts <~ dont want this OU to be searched
Azure Super Accounts <~ dont want this OU to be searched
Disabled Users
# OUs to Exclude from list - based on OU Name
$excludeOUs = @(
"Domain Controllers",
"Computers - Unsorted",
"Non-Syncing OU",
"PDX",
"Trackside",
"Z_MigrationTest",
"Arlington",
"Nemacolin",
"Azure"
# Assuming you have OUs with this exact name for exclusion at the OU level
)
# Finds all OUs
$ouQuery = Get-ADOrganizationalUnit -Filter * -SearchBase "DC=ad,DC=chdn,DC=com" -SearchScope OneLevel
# Filtering based on OU Name, not DistinguishedName here
$ouList = $ouQuery | Where-Object { $excludeOUs -notcontains $_.Name }
# Specify output CSV path
$csvPath = "C:\Users\Public\Okta_AD_Company\testmattUsers.csv"
# Check and remove existing CSV to start fresh
If (Test-Path $csvPath) { Remove-Item $csvPath }
# Loop through each OU and gather user info while excluding certain DistinguishedName patterns
foreach ($ou in $ouList) {
Write-Host "`nFinding Users for $ou" -ForegroundColor Cyan
Get-ADUser -Filter * -SearchBase $ou.DistinguishedName -Properties DisplayName, samAccountName, company, DistinguishedName, whenCreated, whenChanged |
Where-Object {
$_.DistinguishedName -notlike "*OU=Disabled Users,*" -and
$_.DistinguishedName -notlike "*OU= $ou Service Accounts,*" -and
$_.DistinguishedName -notlike "*OU= $ou Super Accounts,*"
} |
Select-Object DisplayName, samAccountName, company, DistinguishedName, whenCreated, whenChanged |
Export-Csv -Path $csvPath -NoTypeInformation -Append
}