param( [Parameter(Mandatory)] [string]$Interface, [Parameter(Mandatory)] [string]$IPAddress, [Parameter(Mandatory)] [int]$PrefixLength, [Parameter(Mandatory)] [string]$Gateway, [string]$DnsServers = @("8.8.8.8", "1.1.1.1") ) $ErrorActionPreference = "Stop" # check root if ((id -u) -ne 0) { throw "You have to run 'sudo pwsh'!" } # check NIC $NicExists = Test-Path "/sys/class/net/$Interface" if (-not $NicExists) { throw "NIC interface '$Interface' does not exist." } # Netplan conf $NetplanFile = "/etc/netplan/99-static-ip.yaml" # DNSList to yaml $DnsServersArray = @( $DnsServers -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne "" } ) $DnsList = ($DnsServersArray | ForEach-Object { '"' + $_ + '"' }) -join ', ' Write-Host "DnsServers raw: $DnsServers" Write-Host "DnsServersArray:" $DnsServersArray | ForEach-Object { Write-Host " [$_]" } Write-Host "DnsList: $DnsList" $Yaml = @" network: version: 2 renderer: networkd ethernets: ${Interface}: dhcp4: false addresses: - $IPAddress/$PrefixLength routes: - to: default via: $Gateway nameservers: addresses: [$DnsList] "@ Write-Host "=== Current configuration ===" & ip -br addr show $Interface & ip route Write-Host "" Write-Host "Writing: $NetplanFile" $Yaml | Set-Content ` -Path $NetplanFile ` -Encoding utf8NoBOM # Only rootc can view & chmod 600 $NetplanFile Write-Host "" Write-Host "=== Netplan configuration ===" Get-Content $NetplanFile # Check Netplan conf Write-Host "" Write-Host "Validating Netplan..." & netplan generate if ($LASTEXITCODE -ne 0) { throw "Failed: netplan generate." } # Apply Netplan #Write-Host "Applying Netplan..." #& netplan apply # #if ($LASTEXITCODE -ne 0) { # throw "Failed: netplan apply." #} Write-Host "Scheduling netplan apply..." & /usr/bin/systemd-run ` --unit=netplan-apply-once ` --on-active=2s ` /usr/sbin/netplan apply if ($LASTEXITCODE -ne 0) { throw "Failed to schedule netplan apply." } Write-Host "Netplan apply scheduled. Disconnecting..." exit 0