关于 ms365-tenant-manager
面向 Microsoft 365 全局管理员的指导与自动化技能,用于管理租户设置、用户生命周期和安全策略,并提供 PowerShell 示例及 Python 脚本生成器。
主要功能
- 01租户设置清单与生成器
- 02批量创建用户及离职处理
- 03条件访问与 MFA 工作流
- 04安全审计与 Secure Score 检查
- 05生成 PowerShell 脚本
适用场景
- 01规划新的 Microsoft 365 租户设置
- 02依据结构化输入配置用户
- 03审计策略并准备启用 MFA
- 04处理用户离职和许可证
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alirezarezvani/ claude-skills --skill ms365-tenant-manager安装后在 Claude Code 中输入/ms365-tenant-manager确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
expected_output.jsonsample_input.jsonreferences/powershell-templates.mdsecurity-policies.mdtroubleshooting.mdscripts/powershell_generator.pytenant_setup.pyuser_management.py详细介绍
Microsoft 365 租户管理器
为负责租户设置、用户生命周期、安全策略和组织优化的 Microsoft 365 全局管理员提供专业指导和自动化支持。
快速开始
运行安全审计
Connect-MgGraph -Scopes "Directory.Read.All","Policy.Read.All","AuditLog.Read.All"
Get-MgSubscribedSku | Select-Object SkuPartNumber, ConsumedUnits, @{N="Total";E={$_.PrepaidUnits.Enabled}}
Get-MgPolicyAuthorizationPolicy | Select-Object AllowInvitesFrom, DefaultUserRolePermissions
从 CSV 批量预配用户
# CSV columns: DisplayName, UserPrincipalName, Department, LicenseSku
Import-Csv .\new_users.csv | ForEach-Object {
$passwordProfile = @{ Password = (New-Guid).ToString().Substring(0,16) + "!"; ForceChangePasswordNextSignIn = $true }
New-MgUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName `
-Department $_.Department -AccountEnabled -PasswordProfile $passwordProfile
}
创建条件访问策略(管理员 MFA)
$adminRoles = (Get-MgDirectoryRole | Where-Object { $_.DisplayName -match "Admin" }).Id
$policy = @{
DisplayName = "Require MFA for Admins"
State = "enabledForReportingButNotEnforced" # Start in report-only mode
Conditions = @{ Users = @{ IncludeRoles = $adminRoles } }
GrantControls = @{ Operator = "OR"; BuiltInControls = @("mfa") }
}
New-MgIdentityConditionalAccessPolicy -BodyParameter $policy
内置 Python 生成器
三个仅使用标准库的工具可以确定性地生成 PowerShell 产物。对于批量或可重复的工作,请优先使用它们,而不是手写脚本。示例输入:sample_input.json;预期输出结构:expected_output.json。
# Tenant setup: checklist + DNS records + license plan (JSON), or the full setup script
python3 scripts/tenant_setup.py --config sample_input.json --format json -o tenant_plan.json
python3 scripts/tenant_setup.py --config sample_input.json --format powershell -o tenant_setup.ps1
# User lifecycle: validate first, then generate creation/offboarding scripts
python3 scripts/user_management.py --domain acme.com --action validate --users users.json
python3 scripts/user_management.py --domain acme.com --action create --users users.json -o create_users.ps1
python3 scripts/user_management.py --domain acme.com --action offboard --user-email [email protected] -o offboard.ps1
# Admin scripts: CA policy / security audit / bulk licensing
python3 scripts/powershell_generator.py --tenant-domain acme.com --task conditional-access --policy-config policy.json -o ca_policy.ps1
python3 scripts/powershell_generator.py --tenant-domain acme.com --task security-audit -o audit.ps1
python3 scripts/powershell_generator.py --tenant-domain acme.com --task bulk-license --users-csv users.csv --license-sku ENTERPRISEPACK -o licenses.ps1
门禁: 创建用户前,先运行 --action validate,并确认每个条目都报告 "is_valid": true,然后再生成创建脚本。在租户中运行任何生成的 .ps1 之前,请对照以下工作流逐一审查。
工作流
工作流 1:新租户设置
步骤 1:生成设置清单
运行 python3 scripts/tenant_setup.py --config tenant.json --format json,并逐阶段处理 setup_checklist;dns_records 用于步骤 2,license_recommendations 用于许可证工作流。
在预配之前确认以下前提条件:
- 已创建全局管理员账户,并已通过 MFA 加固
- 已购买自定义域名,且可以编辑 DNS
- 已确认许可证 SKU(需注明 E3 与 E5 的功能要求差异)
步骤 2:配置并验证 DNS 记录
# After adding the domain in the M365 admin center, verify propagation before proceeding
$domain = "company.com"
Resolve-DnsName -Name "_msdcs.$domain" -Type NS -ErrorAction SilentlyContinue
# Also run from a shell prompt:
# nslookup -type=MX company.com
# nslookup -type=TXT company.com # confirm SPF record
在批量创建用户之前,请等待 DNS 传播完成(最长 48 小时)。
步骤 3:应用安全基线
# Disable legacy authentication (blocks Basic Auth protocols)
$policy = @{
DisplayName = "Block Legacy Authentication"
State = "enabled"
Conditions = @{ ClientAppTypes = @("exchangeActiveSync","other") }
GrantControls = @{ Operator = "OR"; BuiltInControls = @("block") }
}
New-MgIdentityConditionalAccessPolicy -BodyParameter $policy
# Enable unified audit log
Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true
步骤 4:预配用户
$licenseSku = (Get-MgSubscribedSku | Where-Object { $_.SkuPartNumber -eq "ENTERPRISEPACK" }).SkuId
Import-Csv .\employees.csv | ForEach-Object {
try {
$user = New-MgUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName `
-AccountEnabled -PasswordProfile @{ Password = (New-Guid).ToString().Substring(0,12)+"!"; ForceChangePasswordNextSignIn = $true }
Set-MgUserLicense -UserId $user.Id -AddLicenses @(@{ SkuId = $licenseSku }) -RemoveLicenses @()
Write-Host "Provisioned: $($_.UserPrincipalName)"
} catch {
Write-Warning "Failed $($_.UserPrincipalName): $_"
}
}
验证: 在 M365 管理中心抽查 3–5 个账户,确认许可证显示为“已激活”。
工作流 2:安全加固
步骤 1:运行安全审计
Connect-MgGraph -Scopes "Directory.Read.All","Policy.Read.All","AuditLog.Read.All","Reports.Read.All"
# Export Conditional Access policy inventory
Get-MgIdentityConditionalAccessPolicy | Select-Object DisplayName, State |
Export-Csv .\ca_policies.csv -NoTypeInformation
# Find accounts without MFA registered
$report = Get-MgReportAuthenticationMethodUserRegistrationDetail
$report | Where-Object { -not $_.IsMfaRegistered } |
Select-Object UserPrincipalName, IsMfaRegistered |
Export-Csv .\no_mfa_users.csv -NoTypeInformation
Write-Host "Audit complete. Review ca_policies.csv and no_mfa_users.csv."
步骤 2:创建 MFA 策略(先仅报告)
$policy = @{
DisplayName = "Require MFA All Users"
State = "enabledForReportingButNotEnforced"
Conditions = @{ Users = @{ IncludeUsers = @("All") } }
GrantControls = @{ Operator = "OR"; BuiltInControls = @("mfa") }
}
New-MgIdentityConditionalAccessPolicy -BodyParameter $policy
验证: 48 小时后,在 Entra ID 中查看登录日志,确认预期用户会被质询,然后将 State 改为 "enabled"。
步骤 3:查看安全评分
# Retrieve current Secure Score and top improvement actions
Get-MgSecuritySecureScore -Top 1 | Select-Object CurrentScore, MaxScore, ActiveUserCount
Get-MgSecuritySecureScoreControlProfile | Sort-Object -Property ActionType |
Select-Object Title, ImplementationStatus, MaxScore | Format-Table -AutoSize
工作流 3:用户离职
步骤 1:阻止登录并撤销会话
$upn = "[email protected]"
$user = Get-MgUser -Filter "userPrincipalName eq '$upn'"
# Block sign-in immediately
Update-MgUser -UserId $user.Id -AccountEnabled:$false
# Revoke all active tokens
Invoke-MgInvalidateAllUserRefreshToken -UserId $user.Id
Write-Host "Sign-in blocked and sessions revoked for $upn"
步骤 2:使用 -WhatIf 预览(移除许可证)
# Identify assigned licenses
$licenses = (Get-MgUserLicenseDetail -UserId $user.Id).SkuId
# Dry-run: print what would be removed
$licenses | ForEach-Object { Write-Host "[WhatIf] Would remove SKU: $_" }
步骤 3:执行离职操作
# Remove licenses
Set-MgUserLicense -UserId $user.Id -AddLicenses @() -RemoveLicenses $licenses
# Convert mailbox to shared (requires ExchangeOnlineManagement module)
Set-Mailbox -Identity $upn -Type Shared
# Remove from all groups
Get-MgUserMemberOf -UserId $user.Id | ForEach-Object {
try { Remove-MgGroupMemberByRef -GroupId $_.Id -DirectoryObjectId $user.Id } catch {}
}
Write-Host "Offboarding complete for $upn"
验证: 在 M365 管理中心确认该账户显示为“已阻止”,没有活动许可证,且邮箱类型为“共享”。
最佳实践
租户设置
- 添加用户之前先启用 MFA
- 为条件访问配置命名位置
- 使用独立的管理员账户并结合 PIM
- 批量创建用户之前,验证自定义域名(及 DNS 传播)
- 应用 Microsoft Secure Score 建议
安全运维
- 条件访问策略先以仅报告模式启动
- 在强制执行新策略之前,查看登录日志 48 小时
- 切勿在脚本中硬编码凭据,请使用 Azure Key Vault 或
Get-Credential - 为所有操作启用统一审计日志
- 定期开展季度安全审查和 Secure Score 检查
PowerShell 自动化
- 优先使用 Microsoft Graph(
Microsoft.Graph模块),而非旧版 MSOnline - 为错误处理添加
try/catch代码块 - 为审计跟踪实现
Write-Host/Write-Warning日志记录 - 在大规模破坏性操作之前,使用
-WhatIf或试运行输出 - 先在非生产租户中测试
参考指南
references/powershell-templates.md
- 即用型脚本模板
- 条件访问策略示例
- 批量用户预配脚本
- 安全审计脚本
references/security-policies.md
- 条件访问配置
- MFA 强制执行策略
- DLP 与保留策略
- 安全基线设置
references/troubleshooting.md
- 常见错误解决方法
- PowerShell 模块问题
- 权限故障排查
- DNS 传播问题
限制
| 约束 | 影响 |
|---|---|
| 需要全局管理员 | 完整的租户设置需要最高权限 |
| API 速率限制 | 批量操作可能会被限流 |
| 许可证依赖 | 高级功能需要 E3/E5 许可证 |
| 混合场景 | 本地 AD 需要额外配置 |
| PowerShell 前置条件 | 需要 Microsoft.Graph 模块 |
所需 PowerShell 模块
Install-Module Microsoft.Graph -Scope CurrentUser
Install-Module ExchangeOnlineManagement -Scope CurrentUser
Install-Module MicrosoftTeams -Scope CurrentUser
所需权限
- 全局管理员 — 完整的租户设置
- 用户管理员 — 用户管理
- 安全管理员 — 安全策略
- Exchange 管理员 — 邮箱管理