I have created the below PowerShell script, but the result is not always correct.
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?
Code: Select all
$filter = '(Enabled -eq $false)'
$ResultDirectory = 'C:\Disabled-ADAccountOutsideOU.csv'
$domainDN = (Get-ADDomain).DistinguishedName
$excludeOUs = @(
'OU=Site1,OU=Disabled Users'
'OU=Site2,OU=Disabled Users'
'OU=SiteX,OU=Disabled Users'
) | ForEach-Object { $_ + ',' + $domainDN }
Get-ADUser -Filter $filter -Properties * |
Where-Object { ($_.SamAccountName.Length -eq 7) -and ($excludeOUs -notcontains $_.ParentContainer) } |
Select-Object -Property SamAccountName, Enabled, @{ n = 'ParentContainer'; e = { $_.DistinguishedName -replace '\A.*?,(?=(CN|OU|DC)=)' } }, CanonicalName, lastlogondate |
Export-Csv -NoTypeInformation -Path $ResultDirectory