-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_W365Graph-AddUsersToLicence.ps1
More file actions
67 lines (52 loc) · 2.4 KB
/
02_W365Graph-AddUsersToLicence.ps1
File metadata and controls
67 lines (52 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Name: 02_W365Graph-AddUsersToLicence
# Created by: Paul Winstanley @sccmentor and Niall Brady @ncbrady
# Documentation:
# Check if Microsoft.Graph.Users module is installed, install if not
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Users)) {
Install-Module Microsoft.Graph.Users -Scope CurrentUser -Force -AllowClobber
}
# Check if Microsoft.Graph.Identity.DirectoryManagement module is installed, install if not
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Identity.DirectoryManagement)) {
Install-Module Microsoft.Graph.Identity.DirectoryManagement -Scope CurrentUser -Force -AllowClobber
}
# Connect to Microsoft Graph
Import-Module Microsoft.Graph.Users
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -Scopes "Group.ReadWrite.All"
# The SKU ID for the license you want to assign
$skuId = "d201f153-d3b2-4057-be2f-fe25c8983e6f"
# Check if the SKU exists
$skuList = Get-MgSubscribedSku | Where-Object { $_.SkuId -eq $skuId }
if (-not $skuList) {
Write-Host "The specified SKU ID '$skuId' does not exist in the tenant. Exiting."
exit
}
# Path to the text file containing UPNs (one per line)
$userIdsFilePath = "C:\temp\userId.txt"
# Read UPNs from the text file
$userIds = Get-Content -Path $userIdsFilePath
# Loop through each UPN and check if the user exists and if the license is already assigned
foreach ($userId in $userIds) {
# Check if the user exists
$user = Get-MgUser -UserId $userId -ErrorAction SilentlyContinue
if (-not $user) {
Write-Host "User $userId does not exist. Skipping."
continue
}
if ($user) {
# Retrieve user license details
$userLicenses = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$userId/licenseDetails"
# Check if the SKU ID is already assigned
$licenseAssigned = $userLicenses.value | Where-Object { $_.skuId -eq $skuId }
if ($licenseAssigned) {
Write-Host "License is already assigned to $userId. Skipping."
} else {
# Assign the license if not already assigned
Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/users/$userId/assignLicense" -Body (@{
addLicenses = @(@{ skuId = $skuId })
removeLicenses = @()
} | ConvertTo-Json) > Null
Write-Host "License assigned to $userId"
}
}
}