简体   繁体   English

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

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

This script work when starting manualy by double click, or from powershell console not started as administrator.此脚本在通过双击手动启动时工作,或者从 powershell 控制台未以管理员身份启动。 This script requires admin privileges.此脚本需要管理员权限。 Script checks if if user account inheritance is disabled (Security-Advanced) and if yes, enables it.脚本检查用户帐户 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
           }
        }

However, it fails from Task Scheduler, somehow it's not running with Admin privileges, user account specified in Task scheduler is domain admin.但是,它从 Task Scheduler 失败,不知何故它没有以管理员权限运行,在 Task scheduler 中指定的用户帐户是域管理员。 Run with highest privileges - checked以最高权限运行 - 选中

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

Tried putting powershell into bat script, again, works manually but not via Scheduler尝试将 powershell 放入 bat 脚本,再次手动工作,但不是通过调度程序

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

Script is running on Domain controller, added "Log on as batch job rigts脚本在域 controller 上运行,添加了“作为批处理作业登录

Error when running through scheduled task:运行定时任务时出错:

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

No error when running manually手动运行不报错

Fixed by disabling UAC and rebooting server通过禁用 UAC 和重启服务器修复

暂无
暂无

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

相关问题 是否会为在Win Server 2008 R2上运行的Windows 7开发PowerShell脚本? - Will a PowerShell script developed for a Windows 7 run on Win Server 2008 R2? Windows Task Scheduler —无法运行Powershell脚本 - Windows Task Scheduler — Fails to run Powershell Scripts ODP.NET 在命令外壳中工作,但作为计划任务失败 (Windows Server 2012 R2) - ODP.NET works in command shell but fails as a scheduled task (Windows Server 2012 R2) PowerShell 服务器 2012 R2 上的计划任务创建错误 - PowerShell Scheduled Task creation error on server 2012 R2 如何在Powershell脚本中将MS Web Deploy安装到Azure Windows Server 2012 R2 VM? - How do I install MS Web Deploy to an Azure Windows Server 2012 R2 VM in a powershell script? Powershell脚本在Windows 2008 R2上运行良好,但在Windows 2012 R2上不执行任何操作 - Powershell script runs fine on Windows 2008 R2 but does nothing on Windows 2012 R2 如何在具有管理员权限的 Windows 任务计划程序中设置 Powershell 脚本? - How to setup a Powershell Script in Windows Task Scheduler with admin permissions? 通过任务计划程序运行时,Azure Powershell脚本失败 - Azure Powershell script fails when run through task scheduler Powershell 新对象在 Windows 任务调度程序运行时失败 - Powershell New-Object fails when run by Windows Task scheduler 通过任务计划程序运行时,导航PowerShell脚本失败 - Navigation powershell script fails when run through task scheduler
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM