Author Posts

August 30, 2016 at 9:47 am

Hi all,

I have script which shows me all disabled users in security groups in OU. Now what I should get it is that I get .csv file with results.

Script:
$searchOU = "OU=,OU=,OU=,DC=test,DC="

Get-ADGroup -Filter 'GroupCategory -eq "Security"' -SearchBase $searchOU | ForEach-Object{ $group = $_
Get-ADGroupMember -Identity $group -Recursive | %{Get-ADUser -Identity $_.distinguishedName -Properties Enabled | ?{$_.Enabled -eq $false}} | ForEach-Object{ $user = $_
$uname = $user.Name
$gname = $group.Name
Write-Output "DisabledUser $uname is a Member of $gname Security Group" -Foreground Yellow
}
}

Thanks

August 30, 2016 at 12:46 pm

You are trying to get a CSV that shows the group and which users are disabled?

August 30, 2016 at 1:04 pm

Correct.

Thanks.

August 30, 2016 at 1:12 pm

Reformatted so your code is a bit more readeable. Not tested, but should be close:

$searchOU = "OU=,OU=,OU=,DC=test,DC="

$results = foreach ( $group in ( Get-ADGroup -Filter 'GroupCategory -eq "Security"' -SearchBase $searchOU ) ) {
    foreach ( $groupMember in ( Get-ADGroupMember -Identity $group -Recursive ) ) {
        $user = Get-ADUser -Identity $groupMember.distinguishedName -Filter "Enabled -eq 'false'"
        if ( $user ) {
            $user | Select Name, @{Name="Group";Expression={$group.Name}}
        }
    }
} 

$results | Export-CSV -Path C:\DisabledUsersInGroups.csv -NoTypeInformation

August 30, 2016 at 2:16 pm

Thanks Rob!

It was very helpful.

The script which is working is below:

$searchOU = "OU=enter your OU,DC=domain,DC=domain"

$results = foreach ( $group in ( Get-ADGroup -Filter 'GroupCategory -eq "Security"' -SearchBase $searchOU ) ) {
foreach ( $groupMember in ( Get-ADGroupMember -Identity $group -Recursive ) ) {
$user = Get-ADUser -Identity $groupMember.distinguishedName -Properties Enabled | ?{$_.Enabled -eq $false}
if ( $user ) {
$user | Select Name, @{Name="Group";Expression={$group.Name}}
}
}
}

$results | Export-CSV -Path C:\DisabledUsersInGroups.csv -NoTypeInformation