Microsoft Entra ID 中的群組型授權的 PowerShell 和 Microsoft Graph 範例
Microsoft Entra 標識符中群組型授權的完整功能可透過 Azure 入口網站 取得,目前有一些實用的工作可以使用現有的 Microsoft Graph 和 Microsoft Graph PowerShell 來執行。 本文件會提供可行功能的範例。
注意
在開始執行 Cmdlet 之前,請先確定您已藉由執行 Connect-MgGraph Cmdlet 來連線到組織。
警告
此程式碼是基於示範目的而提供的範例。 如果您需要在環境中使用此程式碼,請考慮先進行小規模測試,或在個別的測試組織中進行測試。 您可能需要調整程式碼以符合您環境的特定需求。
指派授權至群組
使用下列範例,利用 Microsoft Graph 將授權指派給群組:
POST https://graph.microsoft.com/v1.0/groups/1ad75eeb-7e5a-4367-a493-9214d90d54d0/assignLicense
Content-type: application/json
{
"addLicenses": [
{
"disabledPlans": [ "11b0131d-43c8-4bbb-b2c8-e80f9a50834a" ],
"skuId": "c7df2760-2c81-4ef7-b578-5b5392b571df"
},
{
"disabledPlans": [ "a571ebcc-fqe0-4ca2-8c8c-7a284fd6c235" ],
"skuId": "sb05e124f-c7cc-45a0-a6aa-8cf78c946968"
}
],
"removeLicenses": []
}
輸出:
HTTP/1.1 202 Accepted
Content-type: application/json
location: https://graph.microsoft.com/v2/d056d009-17b3-4106-8173-cd3978ada898/directoryObjects/1ad75eeb-7e5a-4367-a493-9214d90d54d0/Microsoft.DirectoryServices.Group
{
"id": "1ad75eeb-7e5a-4367-a493-9214d90d54d0",
"deletedDateTime": null,
"classification": null,
"createdDateTime": "2018-04-18T22:05:03Z",
"securityEnabled": true,
}
檢視指派給群組的產品授權
Get-MgGroup Cmdlet 可用來擷取群組物件並檢查 AssignedLicenses 屬性:它會列出目前指派給群組的所有產品授權。
# Define the group ID
$groupId = "99c4216a-56de-42c4-a4ac-e411cd8c7c41"
# Get the group with the specified ID and its assigned licenses
$group = Get-MgGroup -GroupId $groupId -Property "AssignedLicenses"
# Extract the assigned licenses
$assignedLicenses = $group | Select-Object -ExpandProperty AssignedLicenses
# Extract the SKU IDs from the assigned licenses
$skuIds = $assignedLicenses | Select-Object -ExpandProperty SkuId
# For each SKU ID, get the corresponding SKU part number
$skuPartNumbers = $skuIds | ForEach-Object {
$skuId = $_
$subscribedSku = Get-MgSubscribedSku | Where-Object { $_.SkuId -eq $skuId }
$skuPartNumber = $subscribedSku | Select-Object -ExpandProperty SkuPartNumber
$skuPartNumber
}
# Output the SKU part numbers
$skuPartNumbers
以下是結果:
SkuPartNumber
-------------
ENTERPRISEPREMIUM
EMSPREMIUM
注意
此處所傳回的資料僅限於產品 (SKU) 資訊。 若要產生授權中已停用的服務方案清單,請參閱群組授權的 Microsoft Graph PowerShell 範例。
使用下列範例從 Microsoft Graph 取得相同的資料。
GET https://graph.microsoft.com/v1.0/groups/99c4216a-56de-42c4-a4ac-e411cd8c7c41?$select=assignedLicenses
輸出:
HTTP/1.1 200 OK
{
"value": [
{
"assignedLicenses": [
{
"accountId":"aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
"skuId":"c7df2760-2c81-4ef7-b578-5b5392b571df",
"disabledPlans":[]
},
{
"accountId":"aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
"skuId":" b05e124f-c7cc-45a0-a6aa-8cf78c946968",
"disabledPlans":[]
},
],
}
]
}
取得具有授權的所有群組
您可以執行下列命令來尋找所有已獲得授權的群組︰
Get-MgGroup -All -Property Id, MailNickname, DisplayName, GroupTypes, Description, AssignedLicenses | Where-Object {$_.AssignedLicenses -ne $null }
您可以顯示更多有關已指派之產品的詳細資料︰
# Get all groups with assigned licenses
$groups = Get-MgGroup -All -Property Id, MailNickname, DisplayName, GroupTypes, Description, AssignedLicenses | Where-Object {$_.AssignedLicenses -ne $null }
# Process each group
$groupInfo = foreach ($group in $groups) {
# For each group, get the SKU part numbers of the assigned licenses
$skuPartNumbers = foreach ($skuId in $group.AssignedLicenses.SkuId) {
$subscribedSku = Get-MgSubscribedSku | Where-Object { $_.SkuId -eq $skuId }
$subscribedSku.SkuPartNumber
}
# Create a custom object with the group's object ID, display name, and license SKU part numbers
[PSCustomObject]@{
ObjectId = $group.Id
DisplayName = $group.DisplayName
Licenses = $skuPartNumbers -join ', '
}
}
$groupInfo
以下是結果:
Id DisplayName AssignedLicenses
-- ----------- ----------------
7023a314-6148-4d7b-b33f-6c775572879a EMS E5 – Licensed users EMSPREMIUM
cf41f428-3b45-490b-b69f-a349c8a4c38e PowerBi - Licensed users POWER_BI_STANDARD
962f7189-59d9-4a29-983f-556ae56f19a5 O365 E3 - Licensed users ENTERPRISEPACK
c2652d63-9161-439b-b74e-fcd8228a7074 EMSandOffice {ENTERPRISEPREMIUM,EMSPREMIUM}
取得具有授權之群組的統計資料
您可以針對具有授權的群組提出基本統計資料報告。 在下列範例中,腳本會列出用戶總數、群組已指派授權的用戶計數,以及群組無法指派授權的用戶計數。
# Import User Graph Module
Import-Module Microsoft.Graph.Users
# Authenticate to MS Graph
Connect-MgGraph -Scopes "User.Read.All", "Directory.Read.All", "Group.ReadWrite.All"
#get all groups with licenses
$groups = Get-MgGroup -All -Property LicenseProcessingState, DisplayName, Id, AssignedLicenses | Select-Object displayname, Id, LicenseProcessingState, AssignedLicenses | Select-Object DisplayName, Id, AssignedLicenses -ExpandProperty LicenseProcessingState | Select-Object DisplayName, State, Id, AssignedLicenses | Where-Object {$_.State -eq "ProcessingComplete"}
$groupInfoArray = @()
# Filter the groups to only include those that have licenses assigned
$groups = $groups | Where-Object {$_.AssignedLicenses -ne $null}
# For each group, get the group name, license types, total user count, licensed user count, and license error count
foreach ($group in $groups) {
$groupInfo = New-Object PSObject
$groupInfo | Add-Member -MemberType NoteProperty -Name "Group Name" -Value $group.DisplayName
$groupInfo | Add-Member -MemberType NoteProperty -Name "Group ID" -Value $group.Id
$groupInfo | Add-Member -MemberType NoteProperty -Name "License Types" -Value ($group.AssignedLicenses | Select-Object -ExpandProperty SkuId)
$groupInfo | Add-Member -MemberType NoteProperty -Name "Total User Count" -Value (Get-MgGroupMember -GroupId $group.Id -All | Measure-Object).Count
$groupInfo | Add-Member -MemberType NoteProperty -Name "Licensed User Count" -Value (Get-MgGroupMember -GroupId $group.Id -All | Where-Object {$_. LicenseProcessingState -eq "ProcessingComplete"} | Measure-Object).Count
$groupInfo | Add-Member -MemberType NoteProperty -Name "License Error Count" -Value (Get-MgGroupMember -GroupId $group.Id -All | Where-Object {$_.LicenseProcessingState -eq "ProcessingFailed"} | Measure-Object).Count
$groupInfoArray += $groupInfo
}
# Format the output and print it to the console
$groupInfoArray | Format-Table -AutoSize
結果如下表:
GroupName GroupId GroupLicenses TotalUserCount LicensedUserCount LicenseErrorCount
--------- ------- ------------- -------------- ----------------- -----------------
Dynamics Licen... 9160c903-9f91-4597-8f79-22b6c47eafbf AAD_PREMIUM_P2 0 0 0
O365 E5 - base... 055dcca3-fb75-4398-a1b8-f8c6f4c24e65 ENTERPRISEPREMIUM 2 2 0
O365 E5 - extr... 6b14a1fe-c3a9-4786-9ee4-3a2bb54dcb8e ENTERPRISEPREMIUM 3 3 0
EMS E5 - all s... 7023a314-6148-4d7b-b33f-6c775572879a EMSPREMIUM 2 2 0
PowerBi - Lice... cf41f428-3b45-490b-b69f-a349c8a4c38e POWER_BI_STANDARD 2 2 0
O365 E3 - all ... 962f7189-59d9-4a29-983f-556ae56f19a5 ENTERPRISEPACK 2 2 0
O365 E5 - EXO 102fb8f4-bbe7-462b-83ff-2145e7cdd6ed ENTERPRISEPREMIUM 1 1 0
Access to Offi... 11151866-5419-4d93-9141-0603bbf78b42 STANDARDPACK 4 3 1
取得具有授權錯誤的所有群組
若要尋找包含某些使用者無法指派授權的群組:
# Get all groups that have assigned licenses
$groups = Get-MgGroup -All -Property DisplayName, Id, AssignedLicenses |
Where-Object { $_.AssignedLicenses -ne $null } |
Select-Object DisplayName, Id, AssignedLicenses
# Initialize an array to store group information
$groupInfo = @()
# Iterate over each group
foreach ($group in $groups) {
$groupId = $group.Id
$groupName = $group.DisplayName
# Initialize counters for total members and members with license errors
$totalCount = 0
$licenseErrorCount = 0
# Get all members of the group that have license errors
$members = Get-MgGroupMemberWithLicenseError -GroupId $groupId
# Process each member
foreach ($member in $members) {
$totalCount++
# If the member has a license error (indicated by a non-empty Id), increment the error count
if (![string]::IsNullOrEmpty($member.Id)) {
$licenseErrorCount++
}
}
# Create a custom object with the group's information and counts
$groupInfo += [PSCustomObject]@{
GroupName = $groupName
GroupId = $groupId
TotalUserCount = $totalCount
LicenseErrorCount = $licenseErrorCount
}
}
# Display the groups with licensing errors
$groupInfo | Where-Object { $_.LicenseErrorCount -gt 0 } | Format-Table -Property GroupName, GroupId, TotalUserCount, LicenseErrorCount
結果看起來類似以下範例:
GroupId GroupName TotalUserCount LicenseErrorCount
-- ----------- --------- -----------
11151866-5419-4d93-9141-0603bbf78b42 Access to Office 365 2 2
使用下列命令從 Microsoft Graph 取得相同的資料
GET https://graph.microsoft.com/v1.0/groups?$filter=hasMembersWithLicenseErrors+eq+true
輸出:
HTTP/1.1 200 OK
{
"value":[
{
"odata.type": "Microsoft.DirectoryServices.Group",
"objectType": "Group",
"id": "11151866-5419-4d93-9141-0603bbf78b42",
... # other group properties.
},
{
"odata.type": "Microsoft.DirectoryServices.Group",
"objectType": "Group",
"id": "c57cdc98-0dcd-4f90-a82f-c911b288bab9",
...
},
... # other groups with license errors.
]
"odata.nextLink":"https://graph.microsoft.com/v1.0/ groups?$filter=hasMembersWithLicenseErrors+eq+true&$skipToken=<encodedPageToken>"
}
取得群組中具有授權錯誤的所有使用者
若群組中包含某些授權相關錯誤,您現在可以列出這些錯誤所影響到的使用者。 使用者也可能有來自其他群組的錯誤。 不過,此範例所列出的結果僅限於與有問題之群組有關的錯誤,其方法是對使用者每個 IndirectLicenseError 項目的 ReferencedObjectId 屬性進行檢查。
#a sample group with errors
$groupId = '11151866-5419-4d93-9141-0603bbf78b42'
#get all user members of the group
$Members = Get-MgGroupMember -All -GroupId $groupId
#get full information about user objects
Foreach ($Member in $Members) {
Get-MgUser -UserId $Member.Id |
#filter out users without license errors and users with license errors from other groups
Where {$Member.AdditionalProperties.IndirectLicenseErrors -and $Member.AdditionalProperties.IndirectLicenseErrors.ReferencedObjectId -eq $groupId} |
#display id, name and error detail. Note: we are filtering out license errors from other groups
Select Id, `
DisplayName, `
@{Name="LicenseError";Expression={$Member.AdditionalProperties.IndirectLicenseErrors |
Where {$Member.AdditionalProperties.IndirectLicenseErrors.ReferencedObjectId -eq $groupId} |
Select -ExpandProperty Error}}
}
結果看起來類似以下範例:
Id DisplayName License Error
-- ----------- ------------
11bb11bb-cc22-dd33-ee44-55ff55ff55ff Catherine Gibson MutuallyExclusiveViolation
使用下列命令從 Microsoft Graph 取得相同的資料:
GET https://graph.microsoft.com/v1.0/groups/11151866-5419-4d93-9141-0603bbf78b42/membersWithLicenseErrors
輸出:
HTTP/1.1 200 OK
{
"value":[
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"id": "11bb11bb-cc22-dd33-ee44-55ff55ff55ff",
... # other user properties.
},
... # other users.
],
"odata.nextLink":"https://graph.microsoft.com/v1.0/groups/11151866-5419-4d93-9141-0603bbf78b42/membersWithLicenseErrors?$skipToken=<encodedPageToken>"
}
取得整個組織中具有授權錯誤的所有使用者
下列指令碼可用來取得具有一或多個群組之授權錯誤的所有使用者。 此指令碼會將每位使用者的每個授權錯誤各列印在一個資料列中,以方便您清楚識別每個錯誤的來源。
注意
此指令碼會列舉組織中的所有使用者,因此可能不適合大型組織使用。
Get-MgUser -All | Where {$_.AdditionalProperties.IndirectLicenseErrors } | % {
$user = $_;
$user.AdditionalProperties.IndirectLicenseErrors | % {
New-Object Object |
Add-Member -NotePropertyName UserName -NotePropertyValue $user.DisplayName -PassThru |
Add-Member -NotePropertyName UserId -NotePropertyValue $user.Id -PassThru |
Add-Member -NotePropertyName GroupId -NotePropertyValue $_.AdditionalProperties.IndirectLicenseErrors.ReferencedObjectId -PassThru |
Add-Member -NotePropertyName LicenseError -NotePropertyValue $_.AdditionalProperties.IndirectLicenseErrors -PassThru
}
}
結果看起來類似以下範例:
UserName UserId GroupId LicenseError
-------- ------ ------- ------------
Anna Bergman 00aa00aa-bb11-cc22-dd33-44ee44ee44ee 7946137d-b00d-4336-975e-b1b81b0666d0 MutuallyExclusiveViolation
Catherine Gibson 11bb11bb-cc22-dd33-ee44-55ff55ff55ff f2503e79-0edc-4253-8bed-3e158366466b CountViolation
Catherine Gibson 22cc22cc-dd33-ee44-ff55-66aa66aa66aa 11151866-5419-4d93-9141-0603bbf78b42 MutuallyExclusiveViolation
Drew Fogarty 33dd33dd-ee44-ff55-aa66-77bb77bb77bb 1ebd5028-6092-41d0-9668-129a3c471332 MutuallyExclusiveViolation
以下是另一個版本的指令碼,它只會針對包含授權錯誤的群組進行搜尋。 這個指令碼可能更適合用於預期不會有多少群組有問題的情況。
$groupIds = Get-MgGroup -All -Filter "HasMembersWithLicenseErrors eq true"
foreach ($groupId in $groupIds) {
$Members = Get-MgGroupMember -All -GroupId $groupId
foreach ($Member in $Members) { Get-MgUser -UserId $Member.Id |
Where {$Member.AdditionalProperties.IndirectLicenseErrors -and $Member.AdditionalProperties.IndirectLicenseErrors.ReferencedObjectId -eq $groupId.ObjectID} |
Select DisplayName, `
ObjectId, `
@{Name="LicenseError";Expression={$Member.AdditionalProperties.IndirectLicenseErrors | Where {$Member.AdditionalProperties.IndirectLicenseErrors.ReferencedObjectId -eq $groupId.Id} | Select -ExpandProperty Error}}
}
}
檢查使用者的授權是透過直接指派還是群組繼承而得到
針對用戶物件,可以檢查特定產品授權是否已從群組指派,或是否已直接指派。
下列兩個函式範例可用來分析個別使用者的指派類型︰
#Returns TRUE if the user has the license assigned directly
function UserHasLicenseAssignedDirectly
{
Param([Microsoft.Graph.PowerShell.Models.IMicrosoftGraphUser]$user, [string]$skuId)
foreach($license in $user.Licenses)
{
#we look for the specific license SKU in all licenses assigned to the user
if ($license.AccountSkuId -ieq $skuId)
{
#GroupsAssigningLicense contains a collection of IDs of objects assigning the license
#This could be a group object or a user object (contrary to what the name suggests)
#If the collection is empty, this means the license is assigned directly - this is the case for users who have never been licensed via groups in the past
if ($license.GroupsAssigningLicense.Count -eq 0)
{
return $true
}
#If the collection contains the ID of the user object, this means the license is assigned directly
#Note: the license may also be assigned through one or more groups in addition to being assigned directly
foreach ($assignmentSource in $license.GroupsAssigningLicense)
{
if ($assignmentSource -ieq $user.ObjectId)
{
return $true
}
}
return $false
}
}
return $false
}
#Returns TRUE if the user is inheriting the license from a group
function UserHasLicenseAssignedFromGroup
{
Param([Microsoft.Graph.PowerShell.Models.IMicrosoftGraphUser]$user, [string]$skuId)
foreach($license in $user.Licenses)
{
#we look for the specific license SKU in all licenses assigned to the user
if ($license.AccountSkuId -ieq $skuId)
{
#GroupsAssigningLicense contains a collection of IDs of objects assigning the license
#This could be a group object or a user object (contrary to what the name suggests)
foreach ($assignmentSource in $license.GroupsAssigningLicense)
{
#If the collection contains at least one ID not matching the user ID this means that the license is inherited from a group.
#Note: the license may also be assigned directly in addition to being inherited
if ($assignmentSource -ine $user.ObjectId)
{
return $true
}
}
return $false
}
}
return $false
}
此指令碼會對組織中的每位使用者執行這些函式,使用 SKU 識別碼作為輸入 - 在此範例中我們感興趣的是 Enterprise Mobility + Security 的授權,此授權在我們的組織中是以識別碼 contoso:EMS 表示:
#the license SKU we are interested in. use Get-MgSubscribedSku to see a list of all identifiers in your organization
$skuId = "contoso:EMS"
#find all users that have the SKU license assigned
Get-MgUser -All | where {$_.isLicensed -eq $true -and $_.Licenses.AccountSKUID -eq $skuId} | select `
Id, `
@{Name="SkuId";Expression={$skuId}}, `
@{Name="AssignedDirectly";Expression={(UserHasLicenseAssignedDirectly $_ $skuId)}}, `
@{Name="AssignedFromGroup";Expression={(UserHasLicenseAssignedFromGroup $_ $skuId)}}
結果看起來像下列範例:
Id SkuId AssignedDirectly AssignedFromGroup
-- ----- ---------------- -----------------
157870f6-e050-4b3c-ad5e-0f0a377c8f4d contoso:EMS True False
1f3174e2-ee9d-49e9-b917-e8d84650f895 contoso:EMS False True
240622ac-b9b8-4d50-94e2-dad19a3bf4b5 contoso:EMS True True
Graph 無法直接顯示結果,但可從此 API 來查看:
GET https://graph.microsoft.com/v1.0/users/e61ff361-5baf-41f0-b2fd-380a6a5e406a?$select=licenseAssignmentStates
輸出:
HTTP/1.1 200 OK
{
"value":[
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"id": "e61ff361-5baf-41f0-b2fd-380a6a5e406a",
"licenseAssignmentState":[
{
"skuId": "157870f6-e050-4b3c-ad5e-0f0a377c8f4d",
"disabledPlans":[],
"assignedByGroup": null, # assigned directly.
"state": "Active",
"error": "None"
},
{
"skuId": "1f3174e2-ee9d-49e9-b917-e8d84650f895",
"disabledPlans":[],
"assignedByGroup": "e61ff361-5baf-41f0-b2fd-380a6a5e406a", # assigned by this group.
"state": "Active",
"error": "None"
},
{
"skuId": "240622ac-b9b8-4d50-94e2-dad19a3bf4b5",
"disabledPlans":[
"e61ff361-5baf-41f0-b2fd-380a6a5e406a"
],
"assignedByGroup": "e61ff361-5baf-41f0-b2fd-380a6a5e406a",
"state": "Active",
"error": "None"
},
{
"skuId": "240622ac-b9b8-4d50-94e2-dad19a3bf4b5",
"disabledPlans":[],
"assignedByGroup": null, # It is the same license as the previous one. It means the license is assigned directly once and inherited from group as well.
"state": " Active ",
"error": " None"
}
],
...
}
],
}
移除具有群組授權之使用者的直接授權
此指令碼的目的,是要為已從群組繼承了相同授權的使用者,移除不必要的直接授權;例如,在轉換為群組型授權的過程中進行此操作。
注意
請務必先驗證,要移除的直接授權所啟用的服務功能,沒有比繼承的授權所啟用的功能多。 否則,移除直接授權可能會停用使用者對服務和資料的存取權。 目前無法透過 PowerShell 來檢查哪些服務是透過繼承授權來啟用,哪些則是透過直接授權來啟用。 在指令碼中,我們會指定已知從群組所繼承而來的最低層級服務,然後就此進行檢查,以確定使用者不會意外失去服務的存取權。
#BEGIN: Helper functions used by the script
#Returns TRUE if the user has the license assigned directly
function UserHasLicenseAssignedDirectly
{
Param([Microsoft.Graph.PowerShell.Models.IMicrosoftGraphUser]$user, [string]$skuId)
$license = GetUserLicense $user $skuId
if ($license -ne $null)
{
#GroupsAssigningLicense contains a collection of IDs of objects assigning the license
#This could be a group object or a user object (contrary to what the name suggests)
#If the collection is empty, this means the license is assigned directly - this is the case for users who have never been licensed via groups in the past
if ($license.GroupsAssigningLicense.Count -eq 0)
{
return $true
}
#If the collection contains the ID of the user object, this means the license is assigned directly
#Note: the license may also be assigned through one or more groups in addition to being assigned directly
foreach ($assignmentSource in $license.GroupsAssigningLicense)
{
if ($assignmentSource -ieq $user.ObjectId)
{
return $true
}
}
return $false
}
return $false
}
#Returns TRUE if the user is inheriting the license from a specific group
function UserHasLicenseAssignedFromThisGroup
{
Param([Microsoft.Graph.PowerShell.Models.IMicrosoftGraphUser]$user, [string]$skuId, [Guid]$groupId)
$license = GetUserLicense $user $skuId
if ($license -ne $null)
{
#GroupsAssigningLicense contains a collection of IDs of objects assigning the license
#This could be a group object or a user object (contrary to what the name suggests)
foreach ($assignmentSource in $license.GroupsAssigningLicense)
{
#If the collection contains at least one ID not matching the user ID this means that the license is inherited from a group.
#Note: the license may also be assigned directly in addition to being inherited
if ($assignmentSource -ieq $groupId)
{
return $true
}
}
return $false
}
return $false
}
#Returns the license object corresponding to the skuId. Returns NULL if not found
function GetUserLicense
{
Param([Microsoft.Graph.PowerShell.Models.IMicrosoftGraphUser]$user, [string]$skuId, [Guid]$groupId)
#we look for the specific license SKU in all licenses assigned to the user
foreach($license in $user.Licenses)
{
if ($license.AccountSkuId -ieq $skuId)
{
return $license
}
}
return $null
}
#produces a list of disabled service plan names for a set of plans we want to leave enabled
function GetDisabledPlansForSKU
{
Param([string]$skuId, [string[]]$enabledPlans)
$allPlans = Get-MgSubscribedSku | where {$_.SkuId -ieq $skuId} | Select -ExpandProperty ServiceStatus | Where {$_.ProvisioningStatus -ine "PendingActivation" -and $_.ServicePlan.TargetClass -ieq "User"} | Select -ExpandProperty ServicePlans | Select -ExpandProperty ServiceName
$disabledPlans = $allPlans | Where {$enabledPlans -inotcontains $_}
return $disabledPlans
}
function GetUnexpectedEnabledPlansForUser
{
Param([Microsoft.Graph.PowerShell.Models.IMicrosoftGraphUser]$user, [string]$skuId, [string[]]$expectedDisabledPlans)
$license = GetUserLicense $user $skuId
$extraPlans = @();
if($license -ne $null)
{
$userDisabledPlans = $license.ServiceStatus | where {$_.ProvisioningStatus -ieq "Disabled"} | Select -ExpandProperty ServicePlan | Select -ExpandProperty ServiceName
$extraPlans = $expectedDisabledPlans | where {$userDisabledPlans -notcontains $_}
}
return $extraPlans
}
#END: helper functions
#BEGIN: executing the script
#the group to be processed
$groupId = "48ca647b-7e4d-41e5-aa66-40cab1e19101"
#license to be removed - Office 365 E3
$skuId = "contoso:ENTERPRISEPACK"
#minimum set of service plans we know are inherited from groups - we want to make sure that there aren't any users who have more services enabled
#which could mean that they may lose access after we remove direct licenses
$servicePlansFromGroups = ("EXCHANGE_S_ENTERPRISE", "SHAREPOINTENTERPRISE", "OFFICESUBSCRIPTION")
$expectedDisabledPlans = GetDisabledPlansForSKU $skuId $servicePlansFromGroups
#process all members in the group and get full info about each user in the group looping through group members.
$Members = Get-MgGroupMember -All -GroupId $groupId
Foreach ($member in $Members) {
Get-MgUser -UserId $Member.Id | Foreach {
$user = $_;
$operationResult = "";
#check if Direct license exists on the user
if (UserHasLicenseAssignedDirectly $user $skuId)
{
#check if the license is assigned from this group, as expected
if (UserHasLicenseAssignedFromThisGroup $user $skuId $groupId)
{
#check if there are any extra plans we didn't expect - we are being extra careful not to remove unexpected services
$extraPlans = GetUnexpectedEnabledPlansForUser $user $skuId $expectedDisabledPlans
if ($extraPlans.Count -gt 0)
{
$operationResult = "User has extra plans that may be lost - license removal was skipped. Extra plans: $extraPlans"
}
else
{
#remove the direct license from user
Set-MgUserLicense -UserId $user.Id -RemoveLicenses $skuId
$operationResult = "Removed direct license from user."
}
}
else
{
$operationResult = "User does not inherit this license from this group. License removal was skipped."
}
}
else
{
$operationResult = "User has no direct license to remove. Skipping."
}
#format output
New-Object Object |
Add-Member -NotePropertyName UserId -NotePropertyValue $user.Id -PassThru |
Add-Member -NotePropertyName OperationResult -NotePropertyValue $operationResult -PassThru
} | Format-Table
}
#END: executing the script
結果看起來像下列範例:
UserId OperationResult
------ ---------------
7c7f860f-700a-462a-826c-f50633931362 Removed direct license from user.
0ddacdd5-0364-477d-9e4b-07eb6cdbc8ea User has extra plans that may be lost - license removal was skipped. Extra plans: SHAREPOINTWAC
aadbe4da-c4b5-4d84-800a-9400f31d7371 User has no direct license to remove. Skipping.
注意
執行上述指令碼之前,請先根據您的測試環境,更新變數 $skuId
和 $groupId
的值並將其設為目標,以移除直接授權。
下一步
若要深入了解透過群組管理授權的功能集,請參閱下列文章: