List disabled AD account outside certain OU only and Export to .CSV

343 Views Asked by At

I need to modify the script below to List any AD User account that is disabled outside of the specific OU.

$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

Because at the moment, the problem is the script is exporting some of the users accounts inside the OU=SiteX,OU=Disabled Users OU and nothing is exported or listed under the Default OU CN=Users,DC=Domain,DC=com where some of the Disabled AD account is there?

0

There are 0 best solutions below