I am new to Powershell and I am a bit stuck on looking up 200 staff AD accounts via ‘SamAccountName’ and exporting their access groups (under ‘Member Of’), too an excel sheet in a clean format.
So if staff come back and need access to all the groups again (or some), I would like to look up User ID (SamAccountName) in the excel sheet and just copy data back into AD (or maybe just one or two groups need to be added back in).
This is what I have at the moment but I would like exported csv to have USer ID (SamAccountName) in one Column and access groups in another.
I have Googled; tried various formats and now my mind has just gone blank!
$userlist = Get-Content ‘C:\GS\Get Group List\User.txt’
@kvprasoon: Your implementation would overwrite the CSV for every loop iteration.
@Tom_Mort_Yates: My most common answer to everything, it depends. Guessing from how you are building your code, you learned in another language like vbScript or something as the code isn’t “Powershell’y”. Part of the power of Powershell is the ability to pipe objects to other cmdlets, so you’re not leveraging this functionality when you break things out into separate lines.
The best way that I’ve seen and used to build object is like so (shout out to @Dave Wyatt):
...
#Assign variable to loop, any returns roll up to this variable
$results = foreach($User in $UserList){
Get-ADPrincipalGroupMembership -Identity $User |
Select-Object @{E={$_.Name};L='GroupName'},@{E={$User};L='UserName'}
}
#Pipe all of the results to the CSV
$results | Export-Csv -Path c:\GroupList.csv -NoTypeInformation