Skip to content

Instantly share code, notes, and snippets.

@NotYusta
Last active September 30, 2024 15:27
Show Gist options
  • Save NotYusta/b5e6c4ab4b5da695af801d71f99c104a to your computer and use it in GitHub Desktop.
Save NotYusta/b5e6c4ab4b5da695af801d71f99c104a to your computer and use it in GitHub Desktop.
Windows Automatic Network Configuration
function windows_automatic_network_config {
param (
[string]$IPv4,
[string]$CIDR,
[string]$Gateway,
[string]$DNS1,
[string]$DNS2
)
# Check if all arguments are provided
if (-not $IPv4 -or -not $CIDR -or -not $Gateway -or -not $DNS1 -or -not $DNS2) {
Write-Host "Usage: .\script.ps1 -IPv4 <ipv4> -CIDR <cidr> -Gateway <gateway> -DNS1 <dns1> -DNS2 <dns2>"
exit 1
}
# Detect the network interface
$interface = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' } | Select-Object -First 1
if (-not $interface) {
Write-Host "No active network interface found."
exit 1
}
# Calculate Subnet Mask from CIDR
$subnetMask = [System.Net.IPNetwork]::Parse("$IPv4/$CIDR").SubnetMask
# Configure the static IP settings
try {
New-NetIPAddress -InterfaceAlias $interface.Name -IPAddress $IPv4 -PrefixLength $CIDR -DefaultGateway $Gateway -ErrorAction Stop
# Set the DNS servers
Set-DnsClientServerAddress -InterfaceAlias $interface.Name -ServerAddresses ($DNS1, $DNS2) -ErrorAction Stop
Write-Host "Network and DNS configuration applied permanently."
} catch {
Write-Host "Failed to apply network settings: $_"
exit 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment