PowerShell脚本需求:批量检查并修正域内GPO指定受托者权限
域内GPO权限批量检查与修改脚本
以下是针对需求编写的PowerShell脚本,实现域内所有GPO指定受托者的权限检查与批量修正:
脚本实现
# 指定需要检查的受托者(格式:域名\用户名/组名) $targetTrustee = "CONTOSO\TestUser" # 获取域内所有GPO $allGPOs = Get-GPO -All foreach ($gpo in $allGPOs) { Write-Host "正在检查GPO: $($gpo.DisplayName)" -ForegroundColor Cyan try { # 获取当前受托者在该GPO上的权限 $permission = Get-GPPermission -Name $gpo.DisplayName -Trustee $targetTrustee -ErrorAction Stop $currentPermission = $permission.Permission # 检查权限状态 if ($currentPermission -ne "Read") { Write-Host "发现权限异常: 当前权限为 $currentPermission,将修改为Read" -ForegroundColor Yellow # 修改权限为Read,-Replace参数确保覆盖现有权限 Set-GPPermission -Name $gpo.DisplayName -Trustee $targetTrustee -PermissionLevel Read -Replace -ErrorAction Stop Write-Host "GPO $($gpo.DisplayName) 权限修改完成" -ForegroundColor Green } else { Write-Host "GPO $($gpo.DisplayName) 权限符合要求(Read)" -ForegroundColor Gray } } catch [Microsoft.GroupPolicy.GPObjectNotFoundException] { # 捕获受托者无权限记录的情况(即Permission为空) Write-Host "GPO $($gpo.DisplayName) 中未找到该受托者的权限记录,将添加Read权限" -ForegroundColor Yellow Set-GPPermission -Name $gpo.DisplayName -Trustee $targetTrustee -PermissionLevel Read -ErrorAction Stop Write-Host "GPO $($gpo.DisplayName) 已添加Read权限" -ForegroundColor Green } catch { # 处理其他异常(如无访问权限) Write-Host "处理GPO $($gpo.DisplayName) 时出错: $($_.Exception.Message)" -ForegroundColor Red } } Write-Host "所有GPO权限检查与修改操作完成" -ForegroundColor Green
关键说明
- 依赖模块:脚本需要
GroupPolicy模块支持,该模块默认在域控制器或安装了RSAT工具的机器上可用 - 权限要求:运行脚本需要域管理员或拥有GPO编辑权限的账户
- 测试建议:首次运行可在
Set-GPPermission命令后添加-WhatIf参数,预览修改操作而不实际执行 - 参数解释:
Get-GPO -All:获取域内所有组策略对象Get-GPPermission:查询指定GPO上的受托者权限,无权限记录时会抛出GPObjectNotFoundExceptionSet-GPPermission -PermissionLevel Read -Replace:将受托者权限设置为Read,-Replace参数会覆盖原有权限(若存在)
内容的提问来源于stack exchange,提问作者Cheero Merrys
相关产品推荐
相关产品推荐

