Set-StrictMode -Version Latest $ErrorActionPreference='Stop' Import-Module (Join-Path $PSScriptRoot 'Unattended.psm1') -DisableNameChecking function ConvertTo-IPv4Value([string]$Address) { if ($Address -notmatch '^(0|[1-9][0-9]{0,2})(\.(0|[1-9][0-9]{0,2})){3}$') { throw "Ungueltige IPv4-Adresse: $Address" } [uint64]$v=0 foreach ($p in $Address.Split('.')) { if ([int]$p -gt 255) { throw "Ungueltige IPv4-Adresse: $Address" }; $v=256*$v+[int]$p } return $v } function ConvertFrom-IPv4Value([uint64]$Value) { return (@(24,16,8,0 | ForEach-Object { ($Value -shr $_) -band 255 }) -join '.') } function Get-WindowsPreparationPlan($Settings) { foreach ($key in @('Windows-Server-Version','Netzwerkkarte','GETAC-IP','Netzpräfix','DHCP von','DHCP bis','Medienordner')) { if ([string]::IsNullOrWhiteSpace($Settings[$key])) { throw "Staging: '$key' fehlt." } } $year=([string]$Settings['Windows-Server-Version']).Trim() if ($year -notmatch '^(?:Windows Server )?(2019|2022|2025)$') { throw 'Windows-Server-Version: 2019, 2022 oder 2025 eintragen. Andere Versionen sind noch nicht vorbereitet.' } $year=$Matches[1] $adapter=([string]$Settings.Netzwerkkarte).Trim() if ($adapter -match '[*?\[\]\x00-\x1f]') { throw 'Netzwerkkarte: exakten Adapternamen ohne Wildcards eintragen.' } if ($Settings['Netzpräfix'] -notmatch '^(?:[1-9]|[12][0-9]|30)$') { throw 'Netzpraefix muss zwischen 1 und 30 liegen.' } $prefix=[int]$Settings['Netzpräfix']; $ip=ConvertTo-IPv4Value $Settings['GETAC-IP'] [uint64]$size=[Math]::Pow(2,32-$prefix); [uint64]$network=[Math]::Floor($ip/$size)*$size; $broadcast=$network+$size-1 $first=ConvertTo-IPv4Value $Settings['DHCP von']; $last=ConvertTo-IPv4Value $Settings['DHCP bis'] if ($ip -le $network -or $ip -ge $broadcast -or $first -le $network -or $last -ge $broadcast -or $first -gt $last -or ($ip -ge $first -and $ip -le $last)) { throw 'GETAC-IP und DHCP-Bereich muessen getrennte nutzbare Adressen desselben Netzes sein.' } $octet=$ip -shr 24 if ($octet -eq 0 -or $octet -eq 127 -or $octet -ge 224 -or (($ip -shr 16) -eq 43518)) { throw 'GETAC-IP darf keine Loopback-, APIPA-, Multicast- oder reservierte Adresse sein.' } $media=([string]$Settings.Medienordner).Trim().TrimEnd('\') if ($media -notmatch '^[a-zA-Z]:\\[^<>:"|?*\x00-\x1f]+$' -or $media -match '(?:^|\\)\.{1,2}(?:\\|$)' -or $media -match '[. ](?:\\|$)') { throw 'Medienordner: lokalen absoluten Unterordner verwenden, z.B. C:\Staging\Medien.' } # Kept separate from media: never put secret answer files in a future webroot. $drive=$media.Substring(0,2) return [pscustomobject]@{ WindowsYear=$year; Adapter=$adapter; IP=[string]$Settings['GETAC-IP']; Prefix=$prefix; ScopeId=(ConvertFrom-IPv4Value $network); SubnetMask=(Get-Netmask $prefix); DHCPStart=[string]$Settings['DHCP von']; DHCPEnd=[string]$Settings['DHCP bis']; MediaDirectory=$media; BootDirectory="$drive\Staging-PXE\Boot"; ScopeName='Stagging-KIS'; ScopeDescription='Managed by Stagging Setup-StagingServer v1' } } function Assert-PreparationState($Plan,$State) { if ($State.ProductType -ne 3) { throw 'Ein eigenstaendiger Windows Server ist erforderlich; kein Client und kein Domain Controller.' } if ($State.PartOfDomain) { throw 'Dieses KIS-Profil ist fuer einen eigenstaendigen Staging-Server. Domaenen-DHCP/AD-Autorisierung nicht automatisch aendern.' } if ($State.Caption -notmatch ("Windows Server.*"+[regex]::Escape($Plan.WindowsYear))) { throw "Windows-Version passt nicht zur Excel ($($Plan.WindowsYear))." } if (@($State.Adapters).Count -ne 1) { throw 'Netzwerkkarte nicht eindeutig gefunden.' } $adapter=@($State.Adapters)[0] if (-not $adapter.HardwareInterface -or $adapter.Status -ne 'Up') { throw 'Der ausgewaehlte physische Netzwerkadapter muss verbunden sein (Status Up).' } if (@($State.DefaultRoutes).Count -gt 0) { throw 'Der Installationsadapter hat ein Standardgateway. Einen dedizierten Adapter ohne Standardroute verwenden.' } foreach ($a in $State.Addresses) { if ($a.PrefixOrigin -eq 'Manual' -and ($a.IPAddress -ne $Plan.IP -or [int]$a.PrefixLength -ne $Plan.Prefix)) { throw 'Abweichende feste IP am Installationsadapter. Vorhandene manuelle Konfiguration wird nicht ersetzt.' } } foreach ($a in $State.OtherAddresses) { if ($a.IPAddress -eq $Plan.IP) { throw 'GETAC-IP ist bereits an einem anderen Adapter konfiguriert.' } $value=ConvertTo-IPv4Value ([string]$a.IPAddress); $otherPrefix=[int]$a.PrefixLength $size=[Math]::Pow(2,32-$otherPrefix); $low=[Math]::Floor($value/$size)*$size; $high=$low+$size-1 $ourLow=ConvertTo-IPv4Value $Plan.ScopeId; $ourHigh=$ourLow+[Math]::Pow(2,32-$Plan.Prefix)-1 if ($low -le $ourHigh -and $high -ge $ourLow) { throw 'Das Installationsnetz ueberlappt ein Netz an einem anderen Adapter.' } } foreach ($scope in $State.Scopes) { if ([string]$scope.ScopeId -ne $Plan.ScopeId -or $scope.Name -ne $Plan.ScopeName -or $scope.Description -ne $Plan.ScopeDescription) { throw 'Vorhandener fremder DHCP-Bereich: keine automatische Uebernahme.' } if ([string]$scope.StartRange -ne $Plan.DHCPStart -or [string]$scope.EndRange -ne $Plan.DHCPEnd -or [string]$scope.SubnetMask -ne $Plan.SubnetMask) { throw 'Vorhandener Staging-Bereich weicht von Excel ab. Kein automatisches Ersetzen bestehender Leases.' } } if (@($State.Scopes6).Count -gt 0) { throw 'Vorhandene DHCPv6-Bereiche: kein dedizierter leerer Staging-DHCP-Server.' } if (@($State.Options).Count -gt 0) { throw 'Vorhandene DHCP-Optionen: vor automatischer Einrichtung manuell pruefen (keine impliziten Router-/PXE-Optionen).' } } function Get-PreparationState($Plan) { $os=Get-CimInstance Win32_OperatingSystem $computer=Get-CimInstance Win32_ComputerSystem $adapters=@(Get-NetAdapter -Physical | Where-Object { $_.Name -ceq $Plan.Adapter }) $addresses=@(); $routes=@(); $ipInterface=@(); $dnsClient=@() if ($adapters.Count -eq 1) { $addresses=@(Get-NetIPAddress -InterfaceIndex $adapters[0].ifIndex -AddressFamily IPv4 -ErrorAction Stop) $routes=@(Get-NetRoute -InterfaceIndex $adapters[0].ifIndex -AddressFamily IPv4 | Where-Object DestinationPrefix -eq '0.0.0.0/0') $ipInterface=@(Get-NetIPInterface -InterfaceIndex $adapters[0].ifIndex -AddressFamily IPv4) $dnsClient=@(Get-DnsClient -InterfaceIndex $adapters[0].ifIndex) } $others=@(Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -cne $Plan.Adapter -and $_.IPAddress -ne '127.0.0.1' }) $feature=Get-WindowsFeature -Name DHCP $scopes=@(); $scopes6=@(); $bindings=@(); $options=@() if ($feature.Installed) { Import-Module DhcpServer $scopes=@(Get-DhcpServerv4Scope); $scopes6=@(Get-DhcpServerv6Scope); $bindings=@(Get-DhcpServerv4Binding) $options=@(Get-DhcpServerv4OptionValue) foreach ($scope in $scopes) { $options+=@(Get-DhcpServerv4OptionValue -ScopeId $scope.ScopeId) } } return [pscustomobject]@{ Caption=$os.Caption; ProductType=$os.ProductType; PartOfDomain=$computer.PartOfDomain; Adapters=$adapters; Addresses=$addresses; IPInterface=$ipInterface; DnsClient=$dnsClient; OtherAddresses=$others; DefaultRoutes=$routes; Scopes=$scopes; Scopes6=$scopes6; Options=$options; Bindings=$bindings; DhcpInstalled=[bool]$feature.Installed } } function Invoke-WindowsPreparation($Plan,$State,[switch]$ActivateDhcp) { Assert-PreparationState $Plan $State $index=$State.Adapters[0].ifIndex if (-not $State.DhcpInstalled) { $installed=Install-WindowsFeature -Name DHCP -IncludeManagementTools if (-not $installed.Success) { throw 'DHCP-Rolle konnte nicht installiert werden.' } if ([string]$installed.RestartNeeded -eq 'Yes') { throw 'DHCP-Rolle installiert. Windows lokal neu starten und dasselbe Skript erneut ausfuehren; kein automatischer Neustart.' } } Import-Module DhcpServer Start-Service -Name DHCPServer $scopeCreated=$false try { # First disable all DHCP bindings and the owned scope, before changing IPs. foreach ($binding in @(Get-DhcpServerv4Binding)) { Set-DhcpServerv4Binding -InterfaceAlias $binding.InterfaceAlias -BindingState $false } foreach ($binding in @(Get-DhcpServerv6Binding)) { Set-DhcpServerv6Binding -InterfaceAlias $binding.InterfaceAlias -BindingState $false } if (@($State.Scopes).Count -gt 0) { Set-DhcpServerv4Scope -ScopeId $Plan.ScopeId -State InActive; $scopeCreated=$true } Set-NetIPInterface -InterfaceIndex $index -AddressFamily IPv4 -Dhcp Disabled foreach ($address in @(Get-NetIPAddress -InterfaceIndex $index -AddressFamily IPv4)) { if ($address.IPAddress -ne $Plan.IP -or $address.PrefixOrigin -ne 'Manual') { Remove-NetIPAddress -InterfaceIndex $index -IPAddress $address.IPAddress -Confirm:$false } } $matching=@($State.Addresses | Where-Object { $_.IPAddress -eq $Plan.IP -and [int]$_.PrefixLength -eq $Plan.Prefix -and $_.PrefixOrigin -eq 'Manual' }) if ($matching.Count -eq 0) { New-NetIPAddress -InterfaceIndex $index -IPAddress $Plan.IP -PrefixLength $Plan.Prefix -AddressFamily IPv4 | Out-Null } # Wait for duplicate address detection, but do not continue after a conflict. $ready=$false for ($i=0; $i -lt 10; $i++) { $address=Get-NetIPAddress -InterfaceIndex $index -AddressFamily IPv4 | Where-Object IPAddress -eq $Plan.IP if ($null -ne $address -and $address.AddressState -eq 'Duplicate') { throw 'Doppelte GETAC-IP im Netz erkannt.' } if ($null -ne $address -and $address.AddressState -eq 'Preferred') { $ready=$true; break } Start-Sleep -Seconds 1 } if (-not $ready) { throw 'GETAC-IP ist noch nicht verwendbar. Verkabelung/IP-Konflikt pruefen.' } Set-DnsClient -InterfaceIndex $index -RegisterThisConnectionsAddress $false foreach ($path in @($Plan.MediaDirectory,$Plan.BootDirectory)) { New-Item -ItemType Directory -Path $path -Force | Out-Null } if (-not $scopeCreated) { Add-DhcpServerv4Scope -Name $Plan.ScopeName -Description $Plan.ScopeDescription -StartRange $Plan.DHCPStart -EndRange $Plan.DHCPEnd -SubnetMask $Plan.SubnetMask -State InActive -LeaseDuration ([TimeSpan]::FromHours(4)) | Out-Null $scopeCreated=$true } Set-DhcpServerv4Binding -InterfaceAlias $Plan.Adapter -BindingState $true # Install-WindowsFeature provides DHCP service firewall rules. Add an # explicit adapter-bound rule so an isolated Public-profile NIC works. $ruleName='Stagging-KIS-DHCPv4' $rule=Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue if ($rule) { Remove-NetFirewallRule -Name $ruleName } New-NetFirewallRule -Name $ruleName -DisplayName 'Stagging KIS DHCPv4' -Direction Inbound -Action Allow -Protocol UDP -LocalPort 67 -RemotePort 68 -InterfaceAlias $Plan.Adapter -Profile Any -Service DHCPServer | Out-Null Set-Service -Name DHCPServer -StartupType Automatic $bindings=@(Get-DhcpServerv4Binding) $target=@($bindings | Where-Object { $_.InterfaceAlias -eq $Plan.Adapter -and $_.BindingState }) $other=@($bindings | Where-Object { $_.InterfaceAlias -ne $Plan.Adapter -and $_.BindingState }) if ($target.Count -ne 1 -or $other.Count -gt 0) { throw 'DHCP-Bindings entsprechen nicht dem Installationsadapter.' } if ($ActivateDhcp) { Set-DhcpServerv4Scope -ScopeId $Plan.ScopeId -State Active } $scope=Get-DhcpServerv4Scope -ScopeId $Plan.ScopeId $expected=if ($ActivateDhcp) { 'Active' } else { 'InActive' } if ([string]$scope.State -ne $expected) { throw 'DHCP-Bereich hat nicht den erwarteten Zustand.' } return [pscustomobject]@{ IP=$Plan.IP; Adapter=$Plan.Adapter; DHCP=$expected; ScopeId=$Plan.ScopeId; BootFiles='Noch nicht bereitgestellt'; MediaDirectory=$Plan.MediaDirectory; BootDirectory=$Plan.BootDirectory } } catch { if ($scopeCreated) { Set-DhcpServerv4Scope -ScopeId $Plan.ScopeId -State InActive -ErrorAction SilentlyContinue } Stop-Service -Name DHCPServer -ErrorAction SilentlyContinue throw } } Export-ModuleMember -Function Get-WindowsPreparationPlan,Assert-PreparationState,Get-PreparationState,Invoke-WindowsPreparation