$NewGroup_displayName = “AAD-Intune-Windows-Roger-test”
$GroupOwner = ‘Roger@.com’
==============================================================================
Initial connections
==============================================================================
Write-host ‘Connect to MSGraph’
Connect-MSGraph -ForceNonInteractive -Quiet # get an auth token for MSGraph
Write-host ‘Connect to MGGraph’
Connect-MgGraph -nowelcome
Write-Host ‘Get my user object ID’ # M
$MyObjectid = (get-mguser -all -filter “Mail eq ‘$GroupOwner'”).id
==============================================================================
Create or locate the group
==============================================================================
Write-Host ‘Look for group’
$newGroup = get-mggroup -Filter “displayname eq ‘$NewGroup_displayName'”
if (-not $newGroup) {
# grab the user object to make the owner
$MyObjectid = (get-mguser -all -filter “Mail eq ‘$GroupOwner'”).id
Write-Host 'Create a new group'
$GroupParams = @{
description = "For testing InTune module commands"
displayName = $NewGroup_displayName
groupTypes = @()
mailEnabled = $false
mailNickname = $NewGroup_displayName
securityEnabled = $true
"owners@odata.bind" = @( #owners is handled carefully
"https://graph.microsoft.com/v1.0/users/$MyObjectid"
)
}
$NewGroup = New-MgGroup -BodyParameter $GroupParams
}
==============================================================================
Add members to the group
==============================================================================
$Computernames = @(‘a’,’b,’c’,’d’,’e’)
Remove any that are already a member or invalid names / not found
$GroupMembers = (Get-MgGroupMember -GroupId $NewGroup.Id).additionalproperties.displayName
$ComputernamesFiltered = [System.Collections.ArrayList]@()
foreach ($Computername in $Computernames) {
if ($GroupMembers -notcontains $Computername ) {
if (get-mgdevice -filter “DisplayName eq ‘$Computername'” ) {
$null = $ComputernamesFiltered.Add($Computername)
}
}
}
build the final params
$deviceURLs = [System.Collections.ArrayList]@()
Foreach ($Computername in $ComputernamesFiltered) {
$DeviceID = (Get-mgdevice -Filter “DisplayName eq ‘$Computername'”).Id
$null = $deviceURLs.Add(“https://graph.microsoft.com/v1.0/directoryObjects/{$DeviceID}”)
}
$MemberParams = @{ “members@odata.bind” = $deviceURLs }
Best effort to add to the group / suppress error output
Update-MgGroup -GroupId $NewGroup.Id -BodyParameter $MemberParams # 2> $null
Get list of group members
(Get-MgGroupMember -GroupId $NewGroup.Id).additionalproperties.displayName
DEMO – Remove a group member
$RemoveThisDeviceID = (get-mgdevice -filter “DisplayName eq ‘a'”).id
Remove-MgGroupMemberByRef -GroupId $NewGroup.Id -DirectoryObjectId $RemoveThisDeviceID