I am having the below code which is giving me the list of ad groups a specific user is part of
Get-Content "C:\Automation Scripts\users.txt" | Get-ADUser | ForEach{
$user = $_
$groups = Get-ADPrincipalGroupMembership $user
$groups | %{ New-Object PSObject -Property @{ User = $user.SamAccountName; Group = $_.SamAccountName } }
} | Export-Csv "C:\Automation Scripts\User_Groups.csv" -NoTypeInformation
It is working fine and I am getting the result, but the result is coming like below
"User","Group"
"A92M7202822","Domain Users"
"A92M7202822","A92GS-505-Central Team Data"
"A92M7202822","A00GRP-AdminAccounts"
"A92A7803642","Protected Users"
"A92A7803642","A00GRP-AdminAccounts"
I need the result in csv like below
User,Group
A92M7202822,"Domain Users
A92GS-505-Central Team Data
A00GRP-AdminAccounts
A92GS-505-Ids-Analytics-Share-A92DFS
A92GS-505-Data-DSICF-DEV
A92GS-505-Data-DSICF-PRD
CFRGRP-FS-FR4000_SSgt_CFIDS_RW"
A92A7803642,"Domain Users
Protected Users
A00GRP-AdminAccounts"
One cell for user and next cell should have all the groups in it.
Please let me know what changes need to be done for this
CodePudding user response:
Try not to use New-Object, instead you can use PSCustomobject. Also, in your script you have used $user.samaccountname as values for both User and Groups. I have replaced group name value with name you may modify it.
$output = @()
$output = Get-Content "C:\Automation Scripts\users.txt" | Get-ADUser | ForEach{
$user = $_
$groups = Get-ADPrincipalGroupMembership $user
[PSCustomObject]@{
'User'= $user.SamAccountName
'Group' = $groups.Name
}
}
$output | Export-Csv "C:\Automation Scripts\User_Groups.csv" -NoTypeInformation
And another efficient way of doing this is like:
$users = Get-Content "C:\Automation Scripts\users.txt"
$output = foreach ($user in $users)
{
$groups = Get-ADPrincipalGroupMembership $user
foreach($group in $groups)
{
[PSCustomObject]@{
User = $user
Group = $group.Name
}
}
}
$output | Export-Csv "C:\Automation Scripts\User_Groups.csv" -NoTypeInformation