Files
SGU-CredentialProvider/scripts/Set-SguCedClientNetwork.ps1

69 lines
4.2 KiB
PowerShell

[CmdletBinding()]
param(
[string]$ConfigurationPath = (Join-Path $PSScriptRoot 'ced-network.json'),
[string[]]$ConnectedInterface = @(),
[string[]]$ConnectedSsid = @()
)
$ErrorActionPreference = 'Stop'
$configuration = [IO.File]::ReadAllText($ConfigurationPath) | ConvertFrom-Json
$computer = Get-CimInstance Win32_ComputerSystem
if (-not $computer.PartOfDomain -or $computer.DomainRole -ne 1 -or
$computer.Domain -ine $configuration.Domain -or $env:COMPUTERNAME -notmatch $configuration.ComputerPattern) { return }
if ($ConnectedInterface.Count -ne $ConnectedSsid.Count) { throw 'Interface and SSID lists differ.' }
[Net.IPAddress]::Parse($configuration.PrimaryAddress) | Out-Null
foreach ($server in $configuration.DnsServers) { [Net.IPAddress]::Parse($server) | Out-Null }
# Preserve unrelated aliases (broker/RustDesk included). Consolidate only our
# previously managed entries; an unmanaged conflicting entry requires review.
$path = Join-Path $env:WINDIR 'System32\drivers\etc\hosts'
$begin = '# LCI CED primary domain controller - begin'
$end = '# LCI CED primary domain controller - end'
$current = [IO.File]::ReadAllText($path)
$without = [regex]::Replace($current, "(?ms)^$([regex]::Escape($begin))\r?\n.*?^$([regex]::Escape($end))\r?\n?", '')
$aliases = @([string]$configuration.PrimaryController, ($configuration.PrimaryController -split '\.')[0], [string]$configuration.Domain)
$coveredAliases = @()
$lines = [Collections.Generic.List[string]]::new()
foreach ($line in ($without -split '\r?\n')) {
$parts = $line -split '#', 2
$tokens = @($parts[0].Trim() -split '\s+' | Where-Object { $_ })
if ($tokens.Count -gt 1 -and @($tokens[1..($tokens.Count-1)] | Where-Object { $_ -in $aliases }).Count) {
if ($line -match '# SGU managed direct enrollment\s*$') {
$remaining = @($tokens[1..($tokens.Count-1)] | Where-Object { $_ -notin $aliases })
if ($remaining.Count) { $lines.Add($tokens[0]+' '+($remaining -join ' ')+' # SGU managed direct enrollment') }
continue
}
if ($tokens[0] -ne $configuration.PrimaryAddress) { throw 'An unmanaged hosts entry conflicts with the primary controller. No hosts changes made.' }
$coveredAliases += @($tokens[1..($tokens.Count-1)] | Where-Object { $_ -in $aliases })
}
$lines.Add($line)
}
$prefix = ($lines -join "`r`n").TrimEnd([char[]]"`r`n")
$missingAliases = @($aliases | Where-Object { $_ -notin $coveredAliases })
$entry = $configuration.PrimaryAddress+' '+($missingAliases -join ' ')
$updated = $(if ($prefix) { $prefix+"`r`n" } else { '' })+$(if ($missingAliases.Count) { "$begin`r`n$entry`r`n$end`r`n" } else { '' })
$hostChanged = $updated -cne $current
if ($hostChanged) {
$backup = Join-Path $env:ProgramData 'LCI-Admin\CED-WiFi\hosts.before-consolidation'
if (-not (Test-Path -LiteralPath $backup)) { Copy-Item -LiteralPath $path -Destination $backup }
[IO.File]::WriteAllText($path, $updated, [Text.UTF8Encoding]::new($false))
Clear-DnsClientCache
}
$dnsChanges = 0
for ($i=0; $i -lt $ConnectedInterface.Count; $i++) {
$adapter = Get-NetAdapter | Where-Object { [guid]$_.InterfaceGuid -eq [guid]$ConnectedInterface[$i] }
if (-not $adapter -or -not $ConnectedSsid[$i]) { continue }
if ($ConnectedSsid[$i] -eq $configuration.Ssid) {
$actual = @((Get-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4).ServerAddresses)
if (($actual -join ',') -ne ($configuration.DnsServers -join ',')) {
Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ServerAddresses $configuration.DnsServers
$dnsChanges++
}
} else {
# Emergency Wi-Fi retains DHCP DNS. The domain NRPT is owned by GPO.
$key = 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\'+([guid]$adapter.InterfaceGuid).ToString('B')
$manual = (Get-ItemProperty -LiteralPath $key -Name NameServer -ErrorAction SilentlyContinue).NameServer
if ($manual) { Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ResetServerAddresses; $dnsChanges++ }
}
}
[pscustomobject]@{HostsChanged=$hostChanged;DnsChanges=$dnsChanges;PrimaryController=$configuration.PrimaryController;DnsServers=@($configuration.DnsServers)}