Page 1 of 1

Exporting Disabled AD user accounts outside specific OU only?

Posted: Mon Nov 19, 2018 8:51 pm
by ITEngineer
Hi People,

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
Any help would be greatly appreciated.

Re: Exporting Disabled AD user accounts outside specific OU only?

Posted: Mon Nov 19, 2018 9:11 pm
by jvierra
There is no such parameter as "parentContainer"

Re: Exporting Disabled AD user accounts outside specific OU only?

Posted: Mon Nov 19, 2018 9:20 pm
by ITEngineer
jvierra wrote: Mon Nov 19, 2018 9:11 pm There is no such parameter as "parentContainer"
No, it was just the column name on the .CSV
so how to fix the script so it is filtering properly.

Re: Exporting Disabled AD user accounts outside specific OU only?

Posted: Mon Nov 19, 2018 9:32 pm
by jvierra

Code: Select all

Get-ADUser -Filter {Enabled -eq $false} -Properties CanonicalName, lastlogondate |
    Where-Object{
        $_.SamAccountName.Length -eq 7 -and
        -not ($excludeOUs -match $_.DistinguishedName)
    }

Re: Exporting Disabled AD user accounts outside specific OU only?

Posted: Mon Nov 19, 2018 9:56 pm
by ITEngineer
jvierra wrote: Mon Nov 19, 2018 9:32 pm

Code: Select all

Get-ADUser -Filter {Enabled -eq $false} -Properties CanonicalName, lastlogondate |
    Where-Object{
        $_.SamAccountName.Length -eq 7 -and
        -not ($excludeOUs -match $_.DistinguishedName)
    }
Ah, I see, But the Disabled AD account in the Users Container is still not reported?

how to include this CN: CN=Users,DC=Domain,DC=com