如何借助输入文件用PowerShell完成M365用户离职全流程处理
修复Microsoft 365离职用户PowerShell脚本的许可证移除问题
你的脚本无法移除许可证主要有三个核心问题:重复调用AzureAD用户查询未做错误处理、直接使用许可证友好名称而非SKU ID、操作顺序不合理(可能导致邮箱被误删),同时$Delegates变量未定义。以下是修改后的完整脚本及说明:
前提准备
- 确保CSV文件包含两列:
Email(离职用户的用户主体名称/邮箱)、Delegate(需要获取共享邮箱完全访问权限的用户邮箱) - 已安装并连接
AzureAD和Exchange Online模块:Install-Module AzureAD -Force Install-Module ExchangeOnlineManagement -Force Connect-AzureAD Connect-ExchangeOnline
修改后的完整脚本
# CSV文件路径 $inputFilePath = "C:\FolderName\FileName.csv" # 读取CSV数据 $userList = Import-Csv -Path $inputFilePath # 获取目标许可证的SKU ID(替换为你实际的许可证名称) $targetLicenseName = "DEVELOPERPACK_E5" $licenseSku = Get-AzureADSubscribedSku | Where-Object { $_.SkuPartNumber -eq $targetLicenseName } if (-not $licenseSku) { Write-Error "未找到许可证 $targetLicenseName,请检查名称是否正确" exit 1 } $licenseSkuId = $licenseSku.SkuId foreach ($user in $userList) { $userEmail = $user.Email.Trim() $delegateEmail = $user.Delegate.Trim() if (-not $userEmail -or -not $delegateEmail) { Write-Warning "CSV中存在无效行,跳过:$($user | Out-String)" continue } try { # 获取离职用户对象 $azureUser = Get-AzureADUser -Filter "UserPrincipalName eq '$userEmail'" -ErrorAction Stop if (-not $azureUser) { Write-Warning "未找到用户:$userEmail,跳过" continue } # 1. 阻止用户登录 Set-AzureADUser -ObjectId $azureUser.ObjectId -AccountEnabled $false -ErrorAction Stop Write-Host "已阻止用户 $userEmail 登录" -ForegroundColor Green # 2. 将邮箱转换为共享邮箱(必须在移除许可证前执行,防止Exchange许可证被移除后邮箱被删除) Set-Mailbox -Identity $userEmail -Type Shared -ErrorAction Stop Write-Host "已将 $userEmail 转换为共享邮箱" -ForegroundColor Green # 3. 移除用户许可证 $currentLicenses = $azureUser.AssignedLicenses | Where-Object { $_.SkuId -eq $licenseSkuId } if ($currentLicenses) { Set-AzureADUserLicense -ObjectId $azureUser.ObjectId -RemoveLicenses $licenseSkuId -ErrorAction Stop Write-Host "已移除 $userEmail 的 $targetLicenseName 许可证" -ForegroundColor Green } else { Write-Host "用户 $userEmail 未分配 $targetLicenseName 许可证,跳过移除操作" -ForegroundColor Yellow } # 4. 分配共享邮箱完全访问权限 Add-MailboxPermission -Identity $userEmail -User $delegateEmail -AccessRights FullAccess -AutoMapping $true -ErrorAction Stop Write-Host "已为 $delegateEmail 分配 $userEmail 的完全访问权限" -ForegroundColor Green } catch { Write-Error "处理用户 $userEmail 时出错:$($_.Exception.Message)" continue } }
关键修改说明
- 许可证SKU ID获取:
Set-AzureADUserLicense需要传入许可证的SKU ID而非友好名称,通过Get-AzureADSubscribedSku查询对应许可证的ID,确保移除操作生效 - 操作顺序调整:先将邮箱转换为共享邮箱,再移除许可证——共享邮箱不需要Exchange许可证,若先移除许可证可能导致邮箱被系统删除
- 变量定义修正:从CSV中读取
Delegate列作为权限分配对象,避免使用未定义的$Delegates变量 - 错误处理优化:添加
try-catch块和用户存在性检查,避免单个用户处理失败导致整个脚本终止,同时输出清晰的操作日志 - 减少重复查询:提前获取用户对象,避免多次调用
Get-AzureADUser提升效率
内容的提问来源于stack exchange,提问作者Victor
相关产品推荐
相关产品推荐

