1

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...

1 Answer 1

1
  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
        }
    }
}
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.