title: PowerShell - Check User is Member of Group X ("Get-MsolGroupMember" vs. "Get-DistributionGroupMember")
body: <p>I have a hard time to check if user X is a member of certain Office 365 groups. I tried the following code:</p>
  
  <pre><code>$members = (Get-MsolGroupMember -GroupObjectId $group.ObjectId -All).ForEach('ObjectId')
  
  if($Office365User.ObjectId -in $members) {
     # ... user already a member of group Y
  }
  </code></pre>
  
  <p>But for an unknown reason returns <code>Get-MsolGroupMember</code>not all members. I added two users 1-2 hour ago and those users are not included in the result set. </p>
  
  <p>My next approach used cmdlet <code>Get-DistributionGroupMember</code> but the object in the collection do not have support property <code>ObjectId</code>. </p>
  
  <p>I currently using this code to test if user X is a member of group Y:</p>
  
  <pre><code>function Test-UserisAlreadyGroupMember() {
      param(
          [PARAMETER(Mandatory)]
          [Microsoft.Online.Administration.Group] 
          $Group,
          [PARAMETER(Mandatory)]
          [Microsoft.Online.Administration.User]
          $Office365User
      )
  
      $isMember = $false;
      if($Group.GroupType -eq [GroupType]::DistributionList) {
  
          $members = (Get-DistributionGroupMember -Identity $Group.EmailAddress).ForEach('PrimarySmtpAddress')  
  
          $isMember = ($Office365User.UserPrincipalName -in $members)  
  
      }
      else {
  
          $members =  (Get-MsolGroupMember -GroupObjectId $group.ObjectId -All).ForEach('ObjectId')
  
          $isMember = ($Office365User.ObjectId -in $members)
      }
      $isMember
  } 
  </code></pre>
  
  <p>This leads to the following questions:</p>
  
  <ol>
  <li>Why returns <code>Get-MsolGroupMember</code> not all members of the group?</li>
  <li>Is it "save" to compare <code>PrimarySmtpAddress</code> with <code>UserPrincipalName</code> (do I have to consider situation where <code>UserPrincipalName</code> is not identical to <code>PrimarySmtpAddress</code>)</li>
  <li>What is a better approach to test if user X is a member of group Y?</li>
  </ol>