繁体   English   中英

Windows Server 2012 R2 - Powershell 脚本 - 以管理员身份运行 - 在任务计划程序中失败发生约束冲突

[英]Windows Server 2012 R2 - Powershell script -Run as Admin - fails in Task Scheduler A constraint violation occurred

此脚本在通过双击手动启动时工作,或者从 powershell 控制台未以管理员身份启动。 此脚本需要管理员权限。 脚本检查用户帐户 inheritance 是否被禁用(安全高级),如果是,则启用它。

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

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

# If parameter is not set, we are propably in non-admin execution. We set it to the current working directory so that
#  the working directory of the elevated execution of this script is the current working directory
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 we are in a non-admin execution. Execute this script as admin
if ((Test-Admin) -eq $false)  {
    if ($shouldAssumeToBeElevated) {
        Write-Output "Elevating did not work :("

    } else {
        #                                                         vvvvv add `-noexit` here for better debugging vvvvv 
        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 #####

# Add actual commands to be executed in elevated mode here:
Write-Output "I get executed in an admin PowerShell"



    # Error handling
    Function Exception {
         $err = $_.Exception.Message
         write-output $err | timestamp >> $LogFile
         return $err  
     }
    
     # Create logs directory and file if not exist
    $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
    }
    
    
    # Truncate log file
      
    # Get number of lines of log file
    $logfileLines = Get-content $LogFile | Measure-Object –Line | select -ExpandProperty Lines
    if($logfileLines -gt '5000') {
        (Get-Content $LogFile | Select-Object -Skip 4000) | Out-File $LogFile
      }
      
    
    
    $users = Get-ADUser -ldapfilter "(objectclass=user)" -searchbase "OU=something.local,DC=example,DC=local"
    
    ForEach($user in $users)
    {
        Try{
            $dn= [ADSI](“LDAP://” + $user)
            $acl= $dn.psbase.objectSecurity
            if ($acl.get_AreAccessRulesProtected()){
                $isProtected = $false # $false to enable inheritance
                                 # $true to disable inheritance
                $preserveInheritance = $true # $true to keep inherited access rules
                                         # $false to remove inherited access rules.
                                         # ignored if isProtected=$false
                $acl.SetAccessRuleProtection($isProtected, $preserveInheritance)
                $dn.psbase.commitchanges()
                $output = ($user.SamAccountName + "|" + `
                        $user.DistinguishedName + `
                        "|inheritance set to enabled")
                write-output $output | timestamp >> $LogFile
              }
             }
          Catch{
               Exception
           }
        }

但是,它从 Task Scheduler 失败,不知何故它没有以管理员权限运行,在 Task scheduler 中指定的用户帐户是域管理员。 以最高权限运行 - 选中

程序/脚本: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe添加 arguments(可选):- -ExecutionPolicy Bypass -file "C:\GPO\enable-inheritance.ps1"开始于(可选): C:\GPO

尝试将 powershell 放入 bat 脚本,再次手动工作,但不是通过调度程序

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

脚本在域 controller 上运行,添加了“作为批处理作业登录

运行定时任务时出错:

Exception calling "CommitChanges" with "0" argument(s): "A constraint violation occurred.

手动运行不报错

通过禁用 UAC 和重启服务器修复

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM