[CmdletBinding()] param( [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', [string]$DomainController = $env:COMPUTERNAME, [string]$GpoName = 'CED - Wi-Fi de salas', [string]$ReaderGroup = 'CED-WiFi-Equipos', [switch]$InstallRefreshTask ) $ErrorActionPreference = 'Stop' Import-Module ActiveDirectory Import-Module GroupPolicy $domain = Get-ADDomain -Server $DomainController Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController | Out-Null $group = Get-ADGroup $ReaderGroup -Server $DomainController if (-not $group.DistinguishedName.EndsWith(",$TargetOuDn",[StringComparison]::OrdinalIgnoreCase)) { throw 'Reader group is outside the target OU.' } $gpo = Get-GPO -Name $GpoName -Server $DomainController -Domain $domain.DNSRoot $gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$($domain.DistinguishedName)" $policyDn = "CN=CED Wi-Fi,CN=IEEE80211,CN=Windows,CN=Microsoft,CN=Machine,$gpoDn" if ($InstallRefreshTask) { # SYSTEM authenticates to AD as this DC. Delegate only these specific # properties; no domain administrator password is stored in a task. $controllerSid = (Get-ADComputer ($DomainController.Split('.')[0]) -Server $DomainController).SID $schemaDn = (Get-ADRootDSE -Server $DomainController).schemaNamingContext foreach ($target in @(@{Dn=$group.DistinguishedName;Attribute='member'},@{Dn=$gpoDn;Attribute='versionNumber'})) { $attribute = Get-ADObject -SearchBase $schemaDn -LDAPFilter "(lDAPDisplayName=$($target.Attribute))" -Server $DomainController -Properties schemaIDGUID $entry = [DirectoryServices.DirectoryEntry]::new("LDAP://$DomainController/$($target.Dn)") try { $acl = $entry.ObjectSecurity $acl.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($controllerSid,[DirectoryServices.ActiveDirectoryRights]::WriteProperty,[Security.AccessControl.AccessControlType]::Allow,[guid]::new([byte[]]$attribute.schemaIDGUID))) $entry.ObjectSecurity=$acl; $entry.CommitChanges() } finally { $entry.Dispose() } } $taskDirectory = 'C:\ProgramData\LCI-Admin\CED-WiFi-Readers' New-Item $taskDirectory -ItemType Directory -Force | Out-Null $fileAcl = [Security.AccessControl.DirectorySecurity]::new() $fileAcl.SetAccessRuleProtection($true,$false) foreach ($sid in 'S-1-5-18','S-1-5-32-544') { $fileAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( [Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) } Set-Acl $taskDirectory $fileAcl $taskScript = Join-Path $taskDirectory 'Sync-SguCedWifiReaders.ps1' if ($PSCommandPath -ine $taskScript) { Copy-Item $PSCommandPath $taskScript -Force } foreach ($value in $TargetOuDn,$DomainController,$GpoName,$ReaderGroup) { if ($value.Contains('"')) { throw 'Task parameter contains an unsupported quote.' } } $arguments = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "{0}" -TargetOuDn "{1}" -DomainController "{2}" -GpoName "{3}" -ReaderGroup "{4}"' -f $taskScript,$TargetOuDn,$DomainController,$GpoName,$ReaderGroup $action = New-ScheduledTaskAction -Execute powershell.exe -Argument $arguments $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 15) Register-ScheduledTask -TaskName 'CED WiFi OU readers refresh' -Action $action -Trigger $trigger -User SYSTEM -RunLevel Highest -Force | Out-Null } $computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController | Where-Object Name -match '^(AF|SD|SI)-') $members = @(Get-ADGroupMember $group -Server $DomainController) $add = @($computers | Where-Object DistinguishedName -notin $members.DistinguishedName) $remove = @($members | Where-Object DistinguishedName -notin $computers.DistinguishedName) if ($add.Count) { Add-ADGroupMember $group -Members $add -Server $DomainController } if ($remove.Count) { Remove-ADGroupMember $group -Members $remove -Server $DomainController -Confirm:$false } $changed = $add.Count -gt 0 -or $remove.Count -gt 0 $entry = [DirectoryServices.DirectoryEntry]::new("LDAP://$DomainController/$policyDn") try { $acl = $entry.ObjectSecurity $rules = @($acl.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier])) foreach ($rule in $rules) { if ($rule.ActiveDirectoryRights -eq [DirectoryServices.ActiveDirectoryRights]::GenericRead -and $rule.IdentityReference.Value -ne $group.SID.Value -and $rule.IdentityReference.Value -notin $computers.SID.Value) { $acl.RemoveAccessRuleSpecific($rule); $changed=$true } } foreach ($computer in $computers) { if ($computer.SID.Value -notin $rules.IdentityReference.Value) { $acl.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($computer.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow));$changed=$true } } if ($changed) { $entry.ObjectSecurity=$acl; $entry.CommitChanges() } } finally { $entry.Dispose() } if ($changed) { $adGpo=Get-ADObject $gpoDn -Server $DomainController -Properties versionNumber $version=([long]$adGpo.versionNumber -band 0xFFFF0000L) -bor (([long]$adGpo.versionNumber+1) -band 0xFFFFL) Set-ADObject $gpoDn -Server $DomainController -Replace @{versionNumber=[int]$version} [IO.File]::WriteAllText("$env:WINDIR\SYSVOL\domain\Policies\{$($gpo.Id)}\GPT.INI","[General]`r`nVersion=$version`r`n",[Text.Encoding]::ASCII) } [pscustomobject]@{TargetOu=$TargetOuDn;Computers=$computers.Count;Added=$add.Count;Removed=$remove.Count;Changed=$changed}