Why is pipeline variable null in my foreach loop?

Viewed 44

I'm not a wizard with PowerShell but I'm decently proficient with it. I have a couple lines below that are producing null values in the pipeline and I can't figure out why.

$GroupList = (Get-AzureADUserMembership -ObjectId $MemberId)
foreach ($Group in $GroupList)
    {
        Remove-AzureADGroupMember -ObjectId $_.ObjectId -MemberId $MemberId
    }

This produces errors like this:

Remove-AzureADGroupMember : Cannot bind argument to parameter 'ObjectId' because it is null.
At line:3 char:57
+                     Remove-AzureADGroupMember -ObjectId $_ -MemberId  ...
+                                                         ~~
    + CategoryInfo          : InvalidData: (:) [Remove-AzureADGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Open.AzureAD16.PowerShell.RemoveGroupMember

What I don't get is that if I run it like below, it works.

$GroupList | ForEach-Object {Remove-AzureADGroupMember -ObjectId $_.ObjectId -MemberId $MemberId}

Why is my $_ null in the first example?

0 Answers
Related