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
Falco
  • 101
  • 1
  • 1
  • 8
  • 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](https://stackoverflow.com/a/60708579/45375). In case you need to create arrays manually, e.g. to create _multiple_ ones, use an efficiently extensible list type - see [here](https://stackoverflow.com/a/60029146/45375). – mklement0 Aug 05 '22 at 13:41

1 Answers1

2

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

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

mklement0
  • 382,024
  • 64
  • 607
  • 775
Falco
  • 101
  • 1
  • 1
  • 8