1

Using PowerShell I retrieve information from multiple ActiveDirectory groups and output it to a single CSV file. To each row I want to add the name of the group, in addition to the information retrieved. How can I achieve this?

Desired Result:

"CN","Department","co","Company","Group"
"ABCDEF","Media","UK","Global Entertainment","XXX"

Current Result:

"CN","Department","co","Company"
"ABCDEF","Media","UK","Global Entertainment"

My PowerShell code:

#Roles to check membership for
$Roles= @(
'XXX' 
'YYY'
)

$FolderName = "C:\"
$OutputAD = @()

foreach ($role in $Roles) {
  $GroupMembers = Get-ADGroupMember -identity $role | select name

  $GroupMembersArray = $GroupMembers | Foreach {"$($_.Name)"}

  $GroupMembersArray | ForEach-Object {
    $UserLookup = Get-ADUser -Filter "Name -eq '$_'" -Properties CN,Department,co,Company | Select-Object CN,Department,co,Company
    $OutputAD +=  $UserLookup
  } 

}

$OutputAD | Export-Csv "$FolderName\Membership $(get-date -Format yyyy-MMM-dd-HH-mm-ss).csv" -NoTypeInformation
1
  • As an aside: Extending arrays in a loop with += is inefficient, because a new array must be created behind the scenes in every iteration, given that arrays are of fixed size; a much more efficient approach is to use a foreach loop as an expression and let PowerShell itself collect the outputs in an array: [array] $outputs = foreach (...) { ... } - see this answer. In case you need to create arrays manually, e.g. to create multiple ones, use an efficiently extensible list type - see here. Commented Aug 5, 2022 at 13:41

1 Answer 1

2

Found the solution. In Select-Object you can add a calculated property.

Example: Select-Object CN,Department,co,Company,@{n='Role';e={$role}}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.