That looks fairly over complicated with so many nested ForEach loops. Let's try and simplify it...
This will load the ActiveDirectory module so we can look up the users in AD. Then it makes the empty array just like you did. Then when it loads up the CSV it selects and expands the NetworkID property and passes that down the pipe. The reason I did this is so that while in the pipe we can just address the string directly instead of an object with the NetworkID property (no $_.NetworkID
needed, just $_
).
Then I pull the user's info from AD, and run a ForEach on the user's MemberOf property, adding an entry for each group just like you did. I formed the New-Object a little differently so the properties are all there to start instead of making an object, then adding a property to it, then adding another property to it. It reads very similarly, but is simpler.
Import-Module ActiveDirectory -ea sc
$out = @()
Import-Csv "$env:userprofile\Desktop\ADUsers.txt" | SELECT -Expand NetworkID | ForEach {
$User = Get-ADUser $_ -Prop MemberOf
ForEach ($group in $User.MemberOf) {
$obj = New-Object -TypeName PSObject -Property @{
UserName = $User.samAccountName
GroupName = $group -replace "(CN=)(.+?)(,OU=.*)", "`$2"
}
$out += $obj
}
}
$out | Format-table -AutoSize
$out | Export-Csv -path $env:userprofile\Desktop\ADUsers.csv –NoTypeInformation
So, like most any AD Group related thing I respond to we have the caveat here... This does not deal with nested groups. If you want to dive into nested groups then things start getting more complicated, and we are best off creating a function to do that. As an example of nested groups you can look at the GetNestedUsers function in the last block of script in my answer to this question.