This script work when starting manualy by double click, or from powershell console not started as administrator. This script requires admin privileges. Script checks if if user account inheritance is disabled (Security-Advanced) and if yes, enables it.
#### 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. 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
Tried putting powershell into bat script, again, works manually but not via Scheduler
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
Error when running through scheduled task:
Exception calling "CommitChanges" with "0" argument(s): "A constraint violation occurred.
No error when running manually
CodePudding user response:
Fixed by disabling UAC and rebooting server