PowerShell-Add User or Device to a Group using MS Graph commands
Ref:
Step 1
To verify that the module is ready to use
1
Get-Module -Name "*graph*"
Step 2
Connect to Graph
1
Connect-MgGraph -Scopes "Group.ReadWrite.All"
or
1
Connect-MgGraph -Scopes "GroupMember.ReadWrite.All", "User.ReadWrite.All"
Step 3
Create a new Group for Device / User as member
1
2
3
4
5
6
7
8
9
10
$groupNameUser = "Userlist" or "Devicelist"
$param = @{
description=$groupName
displayName=$groupName
mailEnabled=$false
securityEnabled=$true
mailNickname=$groupName
}
New-MgGroup @param
Retrieve group by DisplayName
1
Get-MgGroup -Filter "DisplayName eq '$groupName'"
Get the group Id of the new Group
1
$groupId = (Get-MgGroup -Filter "DisplayName eq '$groupName'").Id
Get all the details of the managed devices from Intune
1
2
3
4
$allDevices = Get-MgDeviceManagementManagedDevice -All |`
where-object OperatingSystem -eq "Windows" |`
where-object AzureAdRegistered -eq $true |`
Select-Object Id, AzureAdDeviceId, AzureAdRegistered, OperatingSystem, Model, DeviceName, UserDisplayName, UserID, UserPrincipalName | fl
Step 4
Import a list of the devices with device name/computer name as follow.
1
$csv = Import-Csv -Path "C:\Users\userA\Devices.csv"
Step 5
Get the ObjectId of the Device using DisplayName (ComputerName) from the imported csv file
1
2
3
4
5
6
7
8
9
$objectId=@()
foreach($i in $csv){
$objectId += Get-MgDevice -All |`
Where-Object AccountEnabled -eq $true|`
Where-Object OperatingSystem -eq "Windows" |`
Where-Object DisplayName -eq $i.Name |`
Select-Object -ExpandProperty Id
}
Or
Get the UserId of the Device using DisplayName (ComputerName) from the imported csv file
1
2
3
4
5
6
7
8
9
10
11
$userId=@()
foreach($u in $csv){
$userId += Get-MgDeviceManagementManagedDevice -All |`
Where-Object DeviceName -eq $u.Name |`
where-object OperatingSystem -eq "Windows" |`
where-object AzureAdRegistered -eq $true |`
Select-Object -ExpandProperty UserID
}
Step 6
Add the Devices to the New Group with the objectId
1
2
3
foreach($o in $objectId){
New-MgGroupMember -GroupId $groupId -DirectoryObjectId $o
}
Or
Add the Users to the New Group with the userId
1
2
3
foreach($u in $userId){
New-MgGroupMember -GroupId $groupId -DirectoryObjectId $u
}
This post is licensed under CC BY 4.0 by the author.