Windows Server 2012 R2 - Powershell脚本-以Admin身份运行-在任务调度程序中失败.



此脚本在手动双击启动时工作,或者从powershell控制台以管理员身份启动时工作。该脚本需要管理员权限。脚本检查是否禁用了用户帐户继承(Security-Advanced),如果是,则启用它。

#### 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:gpoinheritance.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
}
}

然而,它在任务调度程序中失败,不知何故它没有以Admin权限运行,任务调度程序中指定的用户帐户是域Admin。以最高权限运行-检查

Prorgram/脚本:C:WindowsSystem32WindowsPowerShellv1.0powershell.exe添加参数(可选):-ExecutionPolicy Bypass -file "C:GPOenable-inheritance.ps1"起始位置(可选):C:GPO

尝试将powershell放入bat脚本,再次手动工作,但不通过Scheduler

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

脚本在域控制器上运行,添加了"Log on as批处理作业权限

运行计划任务时出错:

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

手动运行时无错误

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

最新更新