--- GA: UA-139154617-3 disqus: ericstudio langs: zh-tw --- # 批次更換 Microsoft 365 授權的 PowerShell 腳本範例(補充) 借用保哥的範例:https://blog.miniasp.com/post/2021/09/02/Batch-replace-Office-365-to-Microsoft-365-License-using-PowerShell 只是保哥的例子,不是完整的範例,借這篇把內容補齊而己 ### 安裝 AzureAD Module 系統管理員身分執行 PowerShell 命令提示字元視窗。 執行︰ ``` powershell Install-Module -Name AzureAD ``` ### 確定自己的授權 ``` powershell Get-MsolAccountSku AccountSkuId ActiveUnits WarningUnits ConsumedUnits ------------ ----------- ------------ ------------- sample:POWER_BI_PRO 100 0 0 sample:AAD_BASIC 100 0 0 sample:ENTERPRISEPACK 100 0 0 sample:SPE_E3 100 0 0 ``` 1. 要確定有SPE_E3 才是 Microsoft 365 E3 2. 上面的sample:SPE_E3的 sample 就是下面$AADName裡要填的值 ### 更改授權 ``` powershell $licensePlanList=(Get-AzureADSubscribedSku) $AADName = 'sample' #### 原本保哥的例子裡 並不會列出所有USER,要加上 -All $true 才會列出全部 $users = (Get-AzureADUser -All $true) | Where-Object { $_.UserType -ne 'Guest' } | Select-Object UserPrincipalName foreach ($user in $users) { $userUPN = $user.UserPrincipalName Write-Host "############################# $userUPN #############################" $is_old_license=$false $is_new_license=$false $userList = Get-AzureADUser -ObjectID $userUPN | Select -ExpandProperty AssignedLicenses | Select SkuID $userList | ForEach { $sku=$_.SkuId $licensePlanList | ForEach { If ( $sku -eq $_.ObjectId.substring($_.ObjectId.length - 36, 36) ) { If ( $_.SkuPartNumber -eq 'ENTERPRISEPACK' ) { $is_old_license = $true; Write-Host "Old License:" $_.SkuPartNumber } If ( $_.SkuPartNumber -eq 'SPE_E3' ) { $is_new_license = $true; Write-Host "New License:" $_.SkuPartNumber } } } } if ( $is_old_license -and $is_new_license ) { # 兩個授權都有,只要刪除舊的授權 Write-Host "The 'ENTERPRISEPACK' license should be removed." Set-MsolUserLicense -UserPrincipalName $userUPN -RemoveLicenses "$($AADName):ENTERPRISEPACK" } elseif ( $is_old_license -and (-not $is_new_license)) { # 只有舊的授權,就置換成新的授權 Write-Host "The 'ENTERPRISEPACK' license should be replaced with 'SPE_E3' license $is_old_license" Set-MsolUserLicense -UserPrincipalName $userUPN -AddLicenses "$($AADName):SPE_E3" -RemoveLicenses "$($AADName):ENTERPRISEPACK" } elseif ( (-not $is_old_license) -and ($is_new_license)) { # 只有新的授權,就代表設定正確! Write-Host "The new License 'SPE_E3' is applied correctly." } elseif ( (-not $is_old_license) -and (-not $is_new_license)) { # 兩個授權都沒有,基本上就不特別設定 Write-Host "No License is available on this user." } } ``` P.S. 原本 "$($AADName):ENTERPRISEPACK" 。 保哥的例子裡是單引號,但是我執行起來會發生 Unable to assign this license because it is invalid. Use the Get-MsolAccountSku cmdlet to retrieve a list of valid licenses. 改成雙引號就好了。 ###### tags: `powershell` `Microsoft 365`