I'm using Powershell and trying to export a csv that includes a list of users and all the groups they belong to. Where I'm running into troubles is I want each group to be it's own column, making it easier to compare who belongs to what.
$OU = "OU=Company,DC=Domain,DC=local"
$out = @()
$users = Get-aduser -filter * -SearchBase $OU -properties memberof | Where-Object { $_.enabled -eq "true" }
Foreach ( $user in $users ) {
$group = ($user.memberof -replace 'CN=(.+?),(OU|DC|)=.+','$1') -split (", ")
$obj = New-Object psobject
$obj | Add-Member -membertype noteproperty -name Name -Value $user.name -force
$obj | Add-Member -membertype noteproperty -name Dept -Value (($user.DistinguishedName -replace "CN=$($user.name),OU=") -replace ",OU(.+?),OU=Company,DC=Domain,DC=local") -force
$obj | Add-Member -membertype noteproperty -name Loc -Value (($user.DistinguishedName -replace "CN=$($user.name),OU=(.+?),OU=") -replace ",OU=Company,DC=Domain,DC=local") -force
$group | ForEach-Object {
$obj | Add-Member -membertype noteproperty -name $_ -Value "Y" -force
}
$out += $obj
}
$out |export-csv C:\users.csv -NoTypeInformation
So it's going to search for all users, split the memberof groups and then I want to create a separate column for each group. The problem is the foreach-object loop for each group.
This is what I'm looking for. Say user1 belongs to Group1 and Group2, and user2 belongs to Group1 and Group3,
Name Dept Loc Group1 Group2 Group3
User1 HR CAN Y Y
User2 Sales US Y Y
This works for the first user, but it won't add anymore groups for each user after that, the output with be the following:
Name Dept Loc Group1 Group2
User1 HR CAN Y Y
User2 Sales US Y
What am I missing here? Is this possible?
$Outvariable? the way thatExport-CSVworks means that the first collection item defines the columns. any item with more than props than the 1st will be truncated. ///// the usual solution is to sort the collection by the number of props so that the 1st item has the max number of props OR determine the max number of props in advance and build ALL the items with all those props. - Lee_Dailey.MemberOfitems, split them by the delimiter used, add them all into one bunch, remove the dupes, and use that list for your group name property names. - Lee_Dailey