Home > database >  Export users not in an office 365 security group
Export users not in an office 365 security group

Time:02-02

I need to find users that are not in a office 365 security group. I'm not sure how to proceed after getting the list of all the users in the tenant.

This works for pulling a list of users

Get-MSOLUser -all | Where-Object { $_.isLicensed -eq "True"} | Select-Object UserPrincipalName | Export-Csv -path .\users.csv

I'm not sure where to go from here. This is something like what I'm looking for.

Get-MSOLUser -all | Where-Object { $_.isLicensed -eq "True",-and $_.isNotMemberofGroup "SecurityGroup"} | Select-Object UserPrincipalName | Export-Csv -path .\users.csv

CodePudding user response:

the Cmdlets do not natively provide such features but with PowerShell we can use Compare-Object to check differences between two object arrays:

  1. Fetch all users: $allUsers = Get-MSOLUser -all
  2. Fetch members of your group: $groupMembers = Get-MsolGroupMember -GroupObjectId <Your-Group-ID>
  3. Compare the two arrays: Compare-Object -ReferenceObject $groupMembers -DifferenceObject $allUsers -Property ObjectId
  4. Based on your needs you can filter the above based on the SideIndicator property
  5. Export the results by piping the above with | Export-CsV ...

CodePudding user response:

I don't have a way of testing this but this should be the logic you should follow with this pre-historic module, first get the list of members of your target group (in this case ExampleGroup) and then you can loop over all the users filtering by both conditions:

  1. The user has a License
  2. The user is not a member of the Target Group
$targetGroup = "ExampleGroup"
$groupMembers = Get-MsolGroup $targetGroup | Get-MsolGroupMember

Get-MsolUser -All | ForEach-Object {
    if($_.isLicensed -eq $true -and $_.ObjectId -notin $groupMembers.ObjectId) {
        $_
    }
} | Select-Object UserPrincipalName | Export-Csv -Path .\users.csv
  •  Tags:  
  • Related