1

I am attempting to select an Azure AD group and find all the members.

The script below works just fine.

$name = "App-Markets-Admin"    # AD group name
$group1 = Get-AzureADGroup -Filter "DisplayName eq '$name'"         # Get group
Get-AzureADGroupMember -ObjectId $group1.objectid -All $True        # Get members from group

I am attempting to refactor the above to a single line... which is where I get stuck

Get-AzureADGroup -Filter "DisplayName eq '$name'" | Get-AzureADGroupMember -ObjectId $_.objectid -All $True

That doesn't work.

Get-AzureADGroupMember : Cannot bind argument to parameter 'ObjectId' because it is null.
At line:1 char:86
+ ... me eq '$name'" | Get-AzureADGroupMember -ObjectId $_.objectid -All $T ...
+                                                       ~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-AzureADGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Open.AzureAD16.PowerShell.GetGroupMembers

if i do a select , there is definitely an object ID parameter there

Get-AzureADGroup -Filter "DisplayName eq '$name'" | select objectid                                        


ObjectId
--------
3b995b2a-d962-4556-afd6-e5e92385ga7

But this does work if I iterate it via a loop:

Get-AzureADGroup -Filter "DisplayName eq '$name'" | % {Get-AzureADGroupMember -ObjectId $_.objectid -All $True}

Why do i have to pass it through the pipe into a for-each loop?

If I do the following, it also fails

(Get-AzureADGroup -Filter "DisplayName eq '$name'").objectID | Get-AzureADGroupMember -ObjectId $_ -All $True 

If I do this and store it into a variable it works

$id = (Get-AzureADGroup -Filter "DisplayName eq '$name'").objectID 
Get-AzureADGroupMember -ObjectId $id

Really just trying to understand piping objects better and why it's not working in a single line.

Thanks.

Jon
  • 23
  • 7
  • 3
    Remove the `-ObjectId $_.objectID` part and let PowerShell take care of binding the correct OID via the pipeline instead: `Get-AzureADGroup -Filter "DisplayName eq '$name'" | Get-AzureADGroupMember -All $True` – Mathias R. Jessen Jun 04 '21 at 13:49
  • 2
    In short: The automatic `$_` / `$PSInput` variable is only defined in _script blocks_ that process pipeline input, such as the script blocks passed to `ForEach-Object` and `Where-Object`. No variable reference is needed for cmdlets that bind parameters via the pipeline, assuming compatible input. Otherwise, call the cmdlet from inside a `ForEach-Object` script block in which you use `$_` to refer to the current pipeline input object; see this [answer](https://stackoverflow.com/a/55667981/45375) to the linked duplicate. – mklement0 Jun 04 '21 at 14:44

0 Answers0