theface
theface

Reputation: 151

How to select multiple subobjects of an object in powershell

The goal is to select all users from a list of groups which contains the subojects "Users" with X users. This user list should be written later as batch to an SQL Server. The goal ist to have a table with the user properties and the groupname + id.

To make the selection and mapping faster, i have tried to work with the select command of powershell. But there is a problem when more than one user is in the group

$GroupUsers = @()
foreach ($group in $groups) {
        $GroupUsers = New-Object -TypeName PSObject -Property @{
            UserLoginName = $group.Users.LoginName
            UserTitle     = $group.Users.Title
            UserEmail     = $group.Users.Email
            GroupName     = $group.Title
        } | Select UserLoginName, UserTitle, UserEmail, GroupName

         $GroupUsers+= $GroupUsers

    } 

The output which is generated looks like the following:

UserId        : 33
UserLoginName : WalterX.test.com
UserTitle     : Walter X
UserEmail     : [email protected]
GroupName     : Group1
GroupId       : 1

UserId        : {1, 2, 3, 4...}
UserLoginName : {User1.test.com, User2.test.com,User3.test.com ...}
UserTitle     : {User1,User2,User3...}
UserEmail     : {[email protected],[email protected]...}
GroupName     : Group2
GroupId       : 2

As you can see the first user is exported correctly. The second entry in the array has on the UserLoginName, Title and EMail property multiple users in it...

Upvotes: 1

Views: 1610

Answers (1)

user6811411
user6811411

Reputation:

  1. Don't use +=it's ineffective as it rebuilds the complete array on each addition
  2. Assign the output of the foreach to a variable instead, using a [PSCustomObject]
  3. nest another foreach to iterate the users of the group.
$GroupUsers = foreach($group in $groups) {
    foreach($user in $group.Users){
        [PSCustomObject]@{
            UserLoginName = $User.LoginName
            UserTitle     = $User.Title
            UserEmail     = $User.Email
            GroupName     = $group.Title
        }
    }
}

Upvotes: 1

Related Questions