Get csv from script

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

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

Correct.

Thanks.

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

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