Do I need ForEach-Object when piping users into New-MgGroupMember?

0
0
Asked By MellowCedar42 On

I'm trying to add several users to an Azure AD group with the Microsoft Graph PowerShell cmdlet:

$azureUsers.id | ForEach-Object { New-MgGroupMember -GroupId $group.Id -DirectoryObjectId $_ }

I thought the purpose of piping was to pass each item directly into the next command, so I'm wondering whether there's a way to pipe the IDs straight into New-MgGroupMember without using ForEach-Object. Am I missing a simpler approach, or does this cmdlet only accept one directory object ID at a time?

3 Answers

Answered By QuietOrbit7 On

A pipeline passes objects one at a time, but the receiving cmdlet still has to support pipeline input. New-MgGroupMember doesn’t accept an array of directory object IDs through the pipeline, so it won’t automatically create one membership per ID. In this case, your ForEach-Object is the normal approach: each ID is bound to -DirectoryObjectId and the cmdlet runs once for each user.

MellowCedar42 -

That makes sense. I was remembering other commands that do accept multiple pipeline objects, so I wanted to make sure I wasn’t overlooking something.

Answered By PracticalLynx19 On

Some Microsoft Graph operations support adding multiple members through a batch request, but that introduces batching limits and extra logic. For a regular list of users, looping with ForEach-Object and calling New-MgGroupMember once per ID is straightforward and usually fast enough, even for a few thousand users.

Answered By SilverMaple88 On

The key distinction is that piping does not automatically mean “expand this array as arguments.” It sends each pipeline object to a parameter only when the next command declares pipeline support for that parameter. Since this cmdlet expects a single directory object ID per invocation, the loop is required unless you build a separate Graph batch request.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.