You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows Server 2012 R2计划任务执行PowerShell脚本报错:约束冲突

解决域控制器任务计划执行AD权限继承脚本报错问题

问题背景

脚本用于检查并启用AD用户账户的安全权限继承,需管理员权限。手动双击或在非管理员PowerShell控制台运行正常,但通过Windows任务计划执行时抛出**"A constraint violation occurred"**错误。已配置域管理员为执行账户、勾选「以最高权限运行」、为账户添加「作为批处理作业登录」权限,尝试用批处理包装脚本仍无效,运行环境为域控制器。

原脚本代码

#### START ELEVATE TO ADMIN #####
param(
    [Parameter(Mandatory=$false)]
    [switch]$shouldAssumeToBeElevated,

    [Parameter(Mandatory=$false)]
    [String]$workingDirOverride
)

# 未指定工作目录时,设置为当前目录以保证提权后工作路径一致
if(-not($PSBoundParameters.ContainsKey('workingDirOverride')))
{
   $workingDirOverride = (Get-Location).Path
}

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

# 非管理员模式下自动提权
if ((Test-Admin) -eq $false)  {
    if ($shouldAssumeToBeElevated) {
        Write-Output "提权失败 :("
    } else {
        # 调试时可添加 `-noexit` 参数保留窗口
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" -shouldAssumeToBeElevated -workingDirOverride "{1}"' -f ($myinvocation.MyCommand.Definition, "$workingDirOverride"))
    }
    exit
}

#Set-Location "$workingDirOverride"
##### END ELEVATE TO ADMIN #####

Write-Output "已在管理员PowerShell中执行"

# 错误处理函数
Function Exception {
     $err = $_.Exception.Message
     write-output $err | timestamp >> $LogFile
     return $err  
 }
 
 # 创建日志文件(不存在则新建)
$LogFile = "C:\gpo\inheritance.log"
filter timestamp {"$(Get-Date -Format G): $_"}
  
If (-not(Test-Path -Path $LogFile)){
    New-Item -Path $LogFile -ItemType File -Force -ErrorAction Stop
}

# 截断日志文件(超过5000行时保留最后1000行)
$logfileLines = Get-content $LogFile | Measure-Object –Line | select -ExpandProperty Lines
if($logfileLines -gt 5000) {
    (Get-Content $LogFile | Select-Object -Skip 4000) | Out-File $LogFile
}

# 获取目标OU下的所有用户
$users = Get-ADUser -ldapfilter "(objectclass=user)" -searchbase "OU=something.local,DC=example,DC=local"

ForEach($user in $users)
{
    Try{
        # 修复LDAP绑定:使用用户的DistinguishedName而非对象本身
        $dn= [ADSI](“LDAP://” + $user.DistinguishedName)
        $acl= $dn.psbase.objectSecurity
        if ($acl.get_AreAccessRulesProtected()){
            $isProtected = $false # false表示启用权限继承
            $preserveInheritance = $true # true表示保留已继承的权限规则
            $acl.SetAccessRuleProtection($isProtected, $preserveInheritance)
            $dn.psbase.commitchanges()
            $output = ($user.SamAccountName + "|" + `
                    $user.DistinguishedName + `
                    "|已启用权限继承")
            write-output $output | timestamp >> $LogFile
          }
         }
      Catch{
           Exception
       }
    }

任务计划原配置

  • 程序/脚本:C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  • 添加参数:-ExecutionPolicy Bypass -file "C:\GPO\enable-inheritance.ps1"
  • 起始于:C:\GPO

尝试过的批处理包装脚本

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\GPO\inheritance.ps1""' -Verb RunAs}"

问题根源与解决方案

1. 核心脚本错误修复

原脚本中[ADSI](“LDAP://” + $user)直接拼接AD用户对象,而非用户的DistinguishedName属性,导致LDAP绑定失败触发约束冲突。修改为[ADSI](“LDAP://” + $user.DistinguishedName)即可解决核心报错。

2. 移除冗余提权逻辑

脚本自带的自动提权逻辑,与任务计划已勾选的「以最高权限运行」形成双重提权,易导致权限上下文异常。建议移除脚本中#### START ELEVATE TO ADMIN #####到##### END ELEVATE TO ADMIN #####的全部代码块,保留任务计划的「以最高权限运行」配置。

3. 任务计划参数优化

将任务计划的参数修改为:
-NoProfile -ExecutionPolicy Bypass -File "C:\GPO\enable-inheritance.ps1"
添加-NoProfile避免加载用户配置文件,减少执行干扰。

4. 验证日志目录权限

确认域管理员账户对C:\gpo目录有读写权限,避免日志写入失败导致脚本异常。

内容的提问来源于stack exchange,提问作者overflowed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:15:40