In PSv4+ you can leverage the -PipelineVariable
/ -pv
common parameter to make the output of an earlier pipeline stage available to script blocks used in later pipeline stages:
Import-Csv C:\Users.csv |
ForEach-Object -pv user { Get-AdUser -filter "displayname -eq '$($_.username)'"} |
Get-ADprincipalGroupMembership |
Select-Object @{ n = 'samaccountname'; e = { $user.samaccountname } }, name |
Export-csv -path C:\UserPermiss.csv -NoTypeInformation
Using -pv user
makes the AD user output by Get-AdUser
available as variable $user
in the Select-Object
stage, where it is referenced in the script block of calculated property samaccountname
, pairing the name of the AD user at hand with the name of each AD group they are a member of.
The resulting CSV file would look something like this:
"samaccountname","name"
"jjo","group1"
"jjo","group2"
"sprice","group1"
"sprice","group3"
"sprice","group4"
# ...