#Requires -Version 5.1 [CmdletBinding(SupportsShouldProcess)] param([string]$DomainController = 'SGU-DC01.lci.lasalle.mx') $ErrorActionPreference = 'Stop' if ($env:COMPUTERNAME -ine $DomainController.Split('.')[0]) { throw 'Run on the specified primary DC so AD and SYSVOL are updated together.' } Import-Module ActiveDirectory Import-Module GroupPolicy $domain = Get-ADDomain -Server $DomainController $dn = $domain.DistinguishedName $changes = [Collections.Generic.List[string]]::new() $modified = @{} $ids = @{ Wifi='0f62e905-dacb-4721-9f02-2e21423bb82e' Provider='3b13538e-f7bf-4c26-9dd1-bf261a3378ae' Remote='dddd0dcb-95f2-420a-bfbb-2e179c414ae4' Experience='6332a4e0-2b6d-4b4c-8d88-0a758ba17fb3' ConfigMgr='d882e45d-5e11-4460-98a3-d9ddc6d04bf3' Scom='3437c619-254f-4afe-bbd5-5cbe23116c5d' } $roots = @{} foreach ($key in $ids.Keys) { Get-GPO -Guid $ids[$key] -Domain $domain.DNSRoot -Server $DomainController | Out-Null $roots[$key] = Join-Path $env:WINDIR ("SYSVOL\domain\Policies\{"+$ids[$key]+'}') } function Set-PolicyText([string]$Owner,[string]$Relative,[string]$Text,[Text.Encoding]$Encoding=[Text.UTF8Encoding]::new($false)) { $path = Join-Path $roots[$Owner] $Relative if ((Test-Path -LiteralPath $path) -and [IO.File]::ReadAllText($path) -ceq $Text) { return } if ($PSCmdlet.ShouldProcess($path,'Update consolidated policy file')) { [IO.Directory]::CreateDirectory((Split-Path $path)) | Out-Null [IO.File]::WriteAllText($path,$Text,$Encoding) $modified[$Owner]=$true $changes.Add("$Owner : $Relative") } } foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Repair-SguCedWifi.ps1','Set-SguCedClientNetwork.ps1','ced-network.json','Invoke-SguCedClientEnrollment.ps1') { Set-PolicyText Wifi ('Machine\Scripts\Startup\'+$file) ([IO.File]::ReadAllText((Join-Path $PSScriptRoot $file))) } $wifiScript = "\\$($domain.DNSRoot)\SYSVOL\$($domain.DNSRoot)\Policies\{$($ids.Wifi)}\Machine\Scripts\Startup\Install-SguCedWifiMaintenance.ps1" Set-PolicyText Wifi 'Machine\Scripts\scripts.ini' ("[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$wifiScript`"`r`n") ([Text.Encoding]::Unicode) # Keep the administrators helper and all UI/branding values in this GPO; # remote-access configuration belongs exclusively to the domain-wide GPO. $experienceIni = [IO.File]::ReadAllText((Join-Path $roots.Experience 'Machine\Scripts\scripts.ini')) $startupSection = [regex]::Match($experienceIni,'(?ms)^\[Startup\]\r?\n(?.*?)(?=^\[|\z)') if (-not $startupSection.Success) { throw 'Missing workstation-experience Startup section.' } $entries = @([regex]::Matches($startupSection.Groups['Body'].Value,'(?m)^(\d+)CmdLine=(.*)\r?\n\1Parameters=(.*)\r?$')) if (-not $entries.Count) { throw 'Unexpected workstation-experience startup registration.' } $ini = "[Startup]`r`n"; $index=0 foreach ($entry in $entries) { if ($entry.Groups[3].Value -match 'Enable-SguWorkstationRemoteAccess\.ps1') { continue } $ini += "$($index)CmdLine=$($entry.Groups[2].Value.TrimEnd())`r`n$($index)Parameters=$($entry.Groups[3].Value.TrimEnd())`r`n" $index++ } $experienceUpdated = $experienceIni.Remove($startupSection.Index,$startupSection.Length).Insert($startupSection.Index,$ini) Set-PolicyText Experience 'Machine\Scripts\scripts.ini' $experienceUpdated ([Text.Encoding]::Unicode) $remoteIni = [IO.File]::ReadAllText((Join-Path $roots.Remote 'Machine\Scripts\scripts.ini')) $remoteIni = $remoteIni -replace ' -LocalDnsServer [^\s]+','' -replace ' -FallbackDnsServer [^\s]+','' Set-PolicyText Remote 'Machine\Scripts\scripts.ini' $remoteIni ([Text.Encoding]::Unicode) Set-PolicyText Remote 'Machine\Scripts\Startup\Enable-SguWorkstationRemoteAccess.ps1' ([IO.File]::ReadAllText((Join-Path $PSScriptRoot 'Enable-SguWorkstationRemoteAccess.ps1'))) $providerIni = [IO.File]::ReadAllText((Join-Path $roots.Provider 'Machine\Scripts\scripts.ini')) $match = [regex]::Match($providerIni,'Update-SguCredentialProvider-[0-9.]+\.ps1') if (-not $match.Success) { throw 'Expected one existing verified provider updater.' } $providerRelative = 'Machine\Scripts\Startup\'+$match.Value $updater = [IO.File]::ReadAllText((Join-Path $roots.Provider $providerRelative)) $retirement = '& (Join-Path $PSScriptRoot ''Invoke-SguWorkstationConsolidation.ps1'') | Out-Null' if ($updater -notmatch 'Invoke-SguWorkstationConsolidation') { # Reuse the already pinned package/hash, certificates and version. A marker # alone must not hide a missing COM binary or an obsolete display name. $old = 'if (Test-Path -LiteralPath $markerPath -PathType Leaf) {' $new = @' $providerId = '{D789CFD8-5AD4-489F-9B83-7EB5D9D09335}' $registered = Get-Item "HKLM:\SOFTWARE\Classes\CLSID\$providerId\InprocServer32" -ErrorAction SilentlyContinue $display = Get-Item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers\$providerId" -ErrorAction SilentlyContinue $providerHealthy = $registered -and (Test-Path -LiteralPath $registered.GetValue('')) -and $display -and $display.GetValue('') -eq 'Acceso Institucional' if ((Test-Path -LiteralPath $markerPath -PathType Leaf) -and $providerHealthy) { & (Join-Path $PSScriptRoot 'Invoke-SguWorkstationConsolidation.ps1') | Out-Null '@ if (-not $updater.Contains($old)) { throw 'Provider updater layout changed; inspect before merging.' } $updater = $updater.Replace($old,$new)+"`r`n$retirement`r`n" } Set-PolicyText Provider $providerRelative $updater Set-PolicyText Provider 'Machine\Scripts\Startup\Invoke-SguWorkstationConsolidation.ps1' ([IO.File]::ReadAllText((Join-Path $PSScriptRoot 'Invoke-SguWorkstationConsolidation.ps1'))) foreach ($owner in 'ConfigMgr','Scom') { $relative = 'Machine\Preferences\ScheduledTasks\ScheduledTasks.xml' [xml]$xml = [IO.File]::ReadAllText((Join-Path $roots[$owner] $relative)) $task = $xml.SelectSingleNode('//*[local-name()="Task"]') $triggers = $task.SelectSingleNode('*[local-name()="Triggers"]') if (-not $triggers -or $task.SelectSingleNode('.//*[local-name()="Arguments"]').InnerText -notmatch 'SYSTEMCENTER\.lci\.lasalle\.mx') { throw 'Unexpected agent deployment policy.' } foreach ($time in @($triggers.SelectNodes('*[local-name()="TimeTrigger"]'))) { [void]$triggers.RemoveChild($time) } if (-not $triggers.SelectSingleNode('*[local-name()="EventTrigger"]')) { $event = $xml.CreateElement('EventTrigger',$task.NamespaceURI) $enabled=$xml.CreateElement('Enabled',$task.NamespaceURI);$enabled.InnerText='true';[void]$event.AppendChild($enabled) $subscription=$xml.CreateElement('Subscription',$task.NamespaceURI) $subscription.InnerText='' [void]$event.AppendChild($subscription) $delay=$xml.CreateElement('Delay',$task.NamespaceURI);$delay.InnerText='PT1M';[void]$event.AppendChild($delay) [void]$triggers.AppendChild($event) } $settings=$task.SelectSingleNode('*[local-name()="Settings"]') if (-not $settings.SelectSingleNode('*[local-name()="RestartOnFailure"]')) { $restart=$xml.CreateElement('RestartOnFailure',$task.NamespaceURI) foreach ($pair in @(@('Interval','PT5M'),@('Count','2'))) {$child=$xml.CreateElement($pair[0],$task.NamespaceURI);$child.InnerText=$pair[1];[void]$restart.AppendChild($child)} [void]$settings.AppendChild($restart) } # Ask Windows to validate the actual task schema before writing the GPP. # TASK_VALIDATE_ONLY (1) never registers or launches a task. $scheduler=New-Object -ComObject Schedule.Service $scheduler.Connect() [void]$scheduler.GetFolder('\').RegisterTask('LCI-Consolidation-SchemaValidation',$task.OuterXml,1,'SYSTEM',$null,5,$null) Set-PolicyText $owner $relative $xml.OuterXml } foreach ($owner in @($modified.Keys)) { $gpoDn="CN={$($ids[$owner])},CN=Policies,CN=System,$dn" $ad=Get-ADObject $gpoDn -Server $DomainController -Properties versionNumber $gpt=Join-Path $roots[$owner] 'GPT.INI' $text=[IO.File]::ReadAllText($gpt) $gptVersion=[long]([regex]::Match($text,'(?m)^Version=(\d+)\r?$').Groups[1].Value) $base=[Math]::Max([long]$ad.versionNumber,$gptVersion) $version=($base -band 0xFFFF0000L) -bor (($base+1) -band 0xFFFFL) [IO.File]::WriteAllText($gpt,([regex]::Replace($text,'(?m)^Version=\d+\r?$',"Version=$version")),[Text.Encoding]::ASCII) Set-ADObject $gpoDn -Server $DomainController -Replace @{versionNumber=[int]$version} } if ($PSCmdlet.ShouldProcess('CED - DNS de dominio','Align domain NRPT with the shared CED network configuration')) { & (Join-Path $PSScriptRoot 'Set-SguCedDnsPolicy.ps1') -DomainController $DomainController | Out-Null } $configurationKey='HKLM\Software\Policies\LaSalle\CEDWifi' $currentConfiguration=Get-GPRegistryValue -Guid $ids.Wifi -Domain $domain.DNSRoot -Server $DomainController -Key $configurationKey -ValueName ConfigurationVersion -ErrorAction SilentlyContinue if ((-not $currentConfiguration -or $currentConfiguration.Value -ne 4) -and $PSCmdlet.ShouldProcess('CED - Wi-Fi de salas','Set configuration version 4')) { Set-GPRegistryValue -Guid $ids.Wifi -Domain $domain.DNSRoot -Server $DomainController -Key $configurationKey -ValueName ConfigurationVersion -Type DWord -Value 4 | Out-Null $changes.Add('Wifi : ConfigurationVersion=4') } [pscustomobject]@{Changed=($changes.Count -gt 0);Files=@($changes.ToArray());Gpos=@($modified.Keys);PrimaryController=$DomainController}