Expected: Only export the Disabled AD account outside the Excluded OU lists to .CSV file.
Result:
Some OU like CN=Users, DC=Domain, DC=com which also have some Disabled AD accounts are skipped or not even checked?
The exported.CSV also still contains the Disabled AD account from OU=SiteX, OU=Disabled Users and some other in the Excluded OU?
Search-ADAccount has a -SearchBase - parameter, just as most of the other AD cmdlets. So you can search for disabled accounts and specify the OU you’re after.
Edit: Ooops … stupid me … “Outside cetrain OU” … ignore my post … follow Jefferys recommendation!
The biggest issue is that you are building ‘ParentContainer’ AFTER you are trying to filter on it. Maybe try segregating the code into a more modular approach so that you can step through it easier.
$ResultDirectory = 'C:\Disabled-ADAccountOutsideOU.csv'
#Create you filter
$domainDN = (Get-ADDomain).DistinguishedName
$excludeOUs = @(
'OU=Site1,OU=Disabled Users'
'OU=Site2,OU=Disabled Users'
'OU=SiteX,OU=Disabled Users'
) | ForEach-Object { $_ + ',' + $domainDN }
#Get all disabled users
$disabledUsers = Get-ADUser -Filter {Enabled -eq $false} -Properties SamAccountName, Enabled, DistinguishedName, CanonicalName, LastLogonDate |
Select-Object -Property SamAccountName, Enabled,@{ n='ParentContainer'; e= { $_.DistinguishedName-replace'\A.*?,(?=(CN|OU|DC)=)' } }, CanonicalName, lastlogondate
#Attempt to filter users
$filteredUsers = $disabledUsers | Where-Object { ($_.SamAccountName.Length -eq 7) -and ($excludeOUs -notcontains $_.ParentContainer) }
#Now before you create a CSV, I would do some basic analysis.
$disabledUsers.Count
$filteredUsers.Count
$filteredUsers | Group-Object -Property ParentContainer -NoElement
#Once I know I have what I want, then I would send it to a CSV
$filteredUsers | Export-Csv -Path $ResultDirectory -NoTypeInformation