Add Network Configuration Launcher scripts for managing network adapters

This commit is contained in:
Maddo 2026-02-12 01:06:03 +01:00
commit 7b4176a7eb
2 changed files with 546 additions and 0 deletions

33
NetworkConfig.bat Normal file
View file

@ -0,0 +1,33 @@
@echo off
:: Network Configuration Launcher
:: This batch file launches the PowerShell script with administrator privileges
title Network Adapter Configuration Tool
:: Check if running as administrator
net session >nul 2>&1
if %errorLevel% == 0 (
goto :run_script
) else (
echo Requesting administrator privileges...
goto :elevate
)
:elevate
:: Request administrator elevation
powershell -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
:run_script
:: Run the PowerShell script
cd /d "%~dp0"
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0Set-NetworkAdapter.ps1"
:: Pause if there was an error
if %errorLevel% neq 0 (
echo.
echo An error occurred while running the script.
pause
)
exit /b

513
Set-NetworkAdapter.ps1 Normal file
View file

@ -0,0 +1,513 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Network Adapter Configuration Script
.DESCRIPTION
Allows quick configuration of network adapter IP settings including DHCP and manual configuration
#>
function Show-Header {
Clear-Host
Write-Host "============================================" -ForegroundColor Cyan
Write-Host " Network Adapter Configuration Tool" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""
}
function Get-AdapterChoice {
Show-Header
Write-Host "Available Network Adapters:" -ForegroundColor Yellow
Write-Host ""
while ($true) {
$adapters = Get-NetAdapter | Where-Object { $_.Status -ne 'Disabled' }
if ($adapters.Count -eq 0) {
Write-Host "No active network adapters found!" -ForegroundColor Red
Read-Host "Press Enter to exit"
exit
}
$index = 1
foreach ($adapter in $adapters) {
$status = if ($adapter.Status -eq 'Up') {
"[CONNECTED]"
} else {
"[" + $adapter.Status.ToUpper() + "]"
}
# Get IP address
$ipv4 = Get-NetIPAddress -InterfaceIndex $adapter.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
$ipAddress = if ($ipv4) { $ipv4.IPAddress } else { "No IP" }
# Get MAC address in both formats
$macWindows = $adapter.MacAddress
$macLinux = $macWindows -replace '-', ':'
Write-Host "$index. $($adapter.Name)" -ForegroundColor White
Write-Host " $($adapter.InterfaceDescription) $status" -ForegroundColor Gray
Write-Host " IP: $ipAddress | MAC: $macWindows ($macLinux)" -ForegroundColor Cyan
$index++
}
Write-Host ""
Write-Host "R. Refresh list" -ForegroundColor White
Write-Host "P. Add/Remove from System PATH" -ForegroundColor White
Write-Host "0. Exit" -ForegroundColor Gray
Write-Host ""
do {
$choice = Read-Host "Select adapter number"
if ($choice -eq '0') {
exit
}
if ($choice -in @('P','p')) {
Add-ToSystemPath
return $null
}
if ($choice -in @('R','r')) {
break
}
if ($choice -match '^[0-9]+$') {
$choiceNum = [int]$choice
} else {
$choiceNum = -1
}
} while ($choiceNum -lt 1 -or $choiceNum -gt $adapters.Count)
if ($choice -in @('R','r')) {
Clear-Host
Show-Header
continue
}
return $adapters[$choiceNum - 1]
}
}
function Show-AdapterInfo {
param (
[Parameter(Mandatory=$true)]
$Adapter
)
Show-Header
Write-Host "Adapter: $($Adapter.Name)" -ForegroundColor Green
Write-Host "Description: $($Adapter.InterfaceDescription)" -ForegroundColor White
Write-Host "Status: $($Adapter.Status)" -ForegroundColor $(if ($Adapter.Status -eq 'Up') { 'Green' } else { 'Yellow' })
Write-Host ""
Write-Host "Hardware Information:" -ForegroundColor Yellow
$macWindows = $Adapter.MacAddress
$macLinux = $macWindows -replace '-', ':'
Write-Host " MAC Address: $macWindows (Windows)" -ForegroundColor White
Write-Host " MAC Address: $macLinux (Linux/Unix)" -ForegroundColor White
Write-Host " Link Speed: $($Adapter.LinkSpeed)" -ForegroundColor White
Write-Host ""
$ipConfig = Get-NetIPConfiguration -InterfaceIndex $Adapter.InterfaceIndex -ErrorAction SilentlyContinue
$ipv4 = Get-NetIPAddress -InterfaceIndex $Adapter.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
Write-Host "IPv4 Configuration:" -ForegroundColor Yellow
if ($ipv4) {
Write-Host " IP Address: $($ipv4.IPAddress)" -ForegroundColor White
Write-Host " Subnet Prefix Length: $($ipv4.PrefixLength) ($(Convert-PrefixToSubnetMask $ipv4.PrefixLength))" -ForegroundColor White
Write-Host " DHCP Enabled: $($ipv4.PrefixOrigin -eq 'Dhcp')" -ForegroundColor White
} else {
Write-Host " IP Address: Not configured" -ForegroundColor Gray
}
if ($ipConfig.IPv4DefaultGateway) {
Write-Host " Default Gateway: $($ipConfig.IPv4DefaultGateway.NextHop)" -ForegroundColor White
} else {
Write-Host " Default Gateway: Not configured" -ForegroundColor Gray
}
$dnsServers = Get-DnsClientServerAddress -InterfaceIndex $Adapter.InterfaceIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
if ($dnsServers -and $dnsServers.ServerAddresses) {
Write-Host " DNS Servers:" -ForegroundColor White
foreach ($dns in $dnsServers.ServerAddresses) {
Write-Host " - $dns" -ForegroundColor White
}
} else {
Write-Host " DNS Servers: Not configured" -ForegroundColor Gray
}
Write-Host ""
}
function Convert-PrefixToSubnetMask {
param([int]$PrefixLength)
$mask = ([Math]::Pow(2, 32) - [Math]::Pow(2, (32 - $PrefixLength)))
$bytes = [BitConverter]::GetBytes([UInt32]$mask)
[Array]::Reverse($bytes)
return ($bytes -join '.')
}
function Convert-SubnetMaskToPrefix {
param([string]$SubnetMask)
$octets = $SubnetMask -split '\.'
$binaryString = ''
foreach ($octet in $octets) {
$binaryString += [Convert]::ToString([int]$octet, 2).PadLeft(8, '0')
}
return ($binaryString.ToCharArray() | Where-Object { $_ -eq '1' }).Count
}
function Add-ToSystemPath {
Write-Host ""
Write-Host "Add NetworkConfig to System PATH" -ForegroundColor Yellow
Write-Host "="*50 -ForegroundColor Yellow
Write-Host ""
$scriptPath = Split-Path -Parent $PSCommandPath
# Check current PATH
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
$machinePath = [Environment]::GetEnvironmentVariable('Path', 'Machine')
$isInUserPath = $userPath -split ';' | Where-Object { $_ -eq $scriptPath }
$isInMachinePath = $machinePath -split ';' | Where-Object { $_ -eq $scriptPath }
Write-Host "Script Location: $scriptPath" -ForegroundColor Cyan
Write-Host ""
if ($isInUserPath) {
Write-Host "✓ Already in User PATH" -ForegroundColor Green
}
if ($isInMachinePath) {
Write-Host "✓ Already in System PATH" -ForegroundColor Green
}
if ($isInUserPath -or $isInMachinePath) {
Write-Host ""
Write-Host "Options:" -ForegroundColor Yellow
Write-Host "1. Remove from User PATH" -ForegroundColor White
Write-Host "2. Remove from System PATH" -ForegroundColor White
Write-Host "0. Cancel" -ForegroundColor Gray
Write-Host ""
$choice = Read-Host "Select option"
switch ($choice) {
'1' {
if ($isInUserPath) {
try {
$newPath = ($userPath -split ';' | Where-Object { $_ -ne $scriptPath }) -join ';'
[Environment]::SetEnvironmentVariable('Path', $newPath, 'User')
Write-Host "Successfully removed from User PATH!" -ForegroundColor Green
Write-Host "You may need to restart your terminals for changes to take effect." -ForegroundColor Yellow
}
catch {
Write-Host "Error removing from User PATH: $($_.Exception.Message)" -ForegroundColor Red
}
} else {
Write-Host "Not found in User PATH." -ForegroundColor Yellow
}
}
'2' {
if ($isInMachinePath) {
try {
$newPath = ($machinePath -split ';' | Where-Object { $_ -ne $scriptPath }) -join ';'
[Environment]::SetEnvironmentVariable('Path', $newPath, 'Machine')
Write-Host "Successfully removed from System PATH!" -ForegroundColor Green
Write-Host "You may need to restart your terminals for changes to take effect." -ForegroundColor Yellow
}
catch {
Write-Host "Error removing from System PATH: $($_.Exception.Message)" -ForegroundColor Red
}
} else {
Write-Host "Not found in System PATH." -ForegroundColor Yellow
}
}
}
} else {
Write-Host "Not currently in PATH." -ForegroundColor Gray
Write-Host ""
Write-Host "Where would you like to add it?" -ForegroundColor Yellow
Write-Host "1. User PATH (current user only)" -ForegroundColor White
Write-Host "2. System PATH (all users - requires admin)" -ForegroundColor White
Write-Host "0. Cancel" -ForegroundColor Gray
Write-Host ""
$choice = Read-Host "Select option"
switch ($choice) {
'1' {
try {
$newPath = $userPath.TrimEnd(';') + ';' + $scriptPath
[Environment]::SetEnvironmentVariable('Path', $newPath, 'User')
Write-Host "Successfully added to User PATH!" -ForegroundColor Green
Write-Host "You can now run 'NetworkConfig' from any terminal." -ForegroundColor Green
Write-Host "You may need to restart your terminals for changes to take effect." -ForegroundColor Yellow
}
catch {
Write-Host "Error adding to User PATH: $($_.Exception.Message)" -ForegroundColor Red
}
}
'2' {
try {
$newPath = $machinePath.TrimEnd(';') + ';' + $scriptPath
[Environment]::SetEnvironmentVariable('Path', $newPath, 'Machine')
Write-Host "Successfully added to System PATH!" -ForegroundColor Green
Write-Host "You can now run 'NetworkConfig' from any terminal." -ForegroundColor Green
Write-Host "You may need to restart your terminals for changes to take effect." -ForegroundColor Yellow
}
catch {
Write-Host "Error adding to System PATH: $($_.Exception.Message)" -ForegroundColor Red
Write-Host "Make sure you're running as administrator." -ForegroundColor Yellow
}
}
}
}
Write-Host ""
Read-Host "Press Enter to continue"
}
function Set-DHCPConfiguration {
param (
[Parameter(Mandatory=$true)]
$Adapter
)
Write-Host ""
Write-Host "Setting adapter to DHCP..." -ForegroundColor Yellow
try {
# Remove existing IP configuration
Remove-NetIPAddress -InterfaceIndex $Adapter.InterfaceIndex -Confirm:$false -ErrorAction SilentlyContinue
Remove-NetRoute -InterfaceIndex $Adapter.InterfaceIndex -Confirm:$false -ErrorAction SilentlyContinue
# Set to DHCP
Set-NetIPInterface -InterfaceIndex $Adapter.InterfaceIndex -Dhcp Enabled -ErrorAction Stop
Set-DnsClientServerAddress -InterfaceIndex $Adapter.InterfaceIndex -ResetServerAddresses -ErrorAction Stop
Write-Host "Successfully configured adapter for DHCP!" -ForegroundColor Green
Write-Host "The adapter will now obtain IP settings automatically." -ForegroundColor Green
}
catch {
Write-Host "Error configuring DHCP: $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host ""
Read-Host "Press Enter to continue"
}
function Set-ManualConfiguration {
param (
[Parameter(Mandatory=$true)]
$Adapter
)
Write-Host ""
Write-Host "Manual IP Configuration" -ForegroundColor Yellow
Write-Host "Leave fields blank to skip configuration for that setting" -ForegroundColor Gray
Write-Host ""
# Get IP Address
do {
$ipAddress = Read-Host "Enter IP Address (e.g., 192.168.1.100)"
if ([string]::IsNullOrWhiteSpace($ipAddress)) {
Write-Host "IP Address is required for manual configuration!" -ForegroundColor Red
}
} while ([string]::IsNullOrWhiteSpace($ipAddress))
# Validate IP Address
try {
[System.Net.IPAddress]::Parse($ipAddress) | Out-Null
}
catch {
Write-Host "Invalid IP Address format!" -ForegroundColor Red
Read-Host "Press Enter to return to menu"
return
}
# Get Subnet Mask
do {
$subnetMask = Read-Host "Enter Subnet Mask (e.g., 255.255.255.0) or prefix length (e.g., 24)"
if ([string]::IsNullOrWhiteSpace($subnetMask)) {
Write-Host "Subnet Mask is required for manual configuration!" -ForegroundColor Red
}
} while ([string]::IsNullOrWhiteSpace($subnetMask))
# Convert subnet mask to prefix length
if ($subnetMask -match '^\d{1,2}$') {
$prefixLength = [int]$subnetMask
} else {
try {
$prefixLength = Convert-SubnetMaskToPrefix $subnetMask
}
catch {
Write-Host "Invalid Subnet Mask format!" -ForegroundColor Red
Read-Host "Press Enter to return to menu"
return
}
}
# Get Default Gateway (optional)
$gateway = Read-Host "Enter Default Gateway (press Enter to skip)"
if (![string]::IsNullOrWhiteSpace($gateway)) {
try {
[System.Net.IPAddress]::Parse($gateway) | Out-Null
}
catch {
Write-Host "Invalid Gateway format!" -ForegroundColor Red
Read-Host "Press Enter to return to menu"
return
}
}
# Get DNS Servers (optional)
$dnsServers = @()
$dns1 = Read-Host "Enter Primary DNS Server (press Enter to skip)"
if (![string]::IsNullOrWhiteSpace($dns1)) {
try {
[System.Net.IPAddress]::Parse($dns1) | Out-Null
$dnsServers += $dns1
}
catch {
Write-Host "Invalid DNS Server format!" -ForegroundColor Red
Read-Host "Press Enter to return to menu"
return
}
}
$dns2 = Read-Host "Enter Secondary DNS Server (press Enter to skip)"
if (![string]::IsNullOrWhiteSpace($dns2)) {
try {
[System.Net.IPAddress]::Parse($dns2) | Out-Null
$dnsServers += $dns2
}
catch {
Write-Host "Invalid DNS Server format!" -ForegroundColor Red
Read-Host "Press Enter to return to menu"
return
}
}
# Confirm configuration
Write-Host ""
Write-Host "Configuration Summary:" -ForegroundColor Cyan
Write-Host " IP Address: $ipAddress/$prefixLength" -ForegroundColor White
if (![string]::IsNullOrWhiteSpace($gateway)) {
Write-Host " Gateway: $gateway" -ForegroundColor White
}
if ($dnsServers.Count -gt 0) {
Write-Host " DNS Servers: $($dnsServers -join ', ')" -ForegroundColor White
}
Write-Host ""
$confirm = Read-Host "Apply this configuration? (Y/N)"
if ($confirm -ne 'Y' -and $confirm -ne 'y') {
Write-Host "Configuration cancelled." -ForegroundColor Yellow
Read-Host "Press Enter to continue"
return
}
# Apply configuration
Write-Host ""
Write-Host "Applying configuration..." -ForegroundColor Yellow
try {
# Remove existing IP configuration
Remove-NetIPAddress -InterfaceIndex $Adapter.InterfaceIndex -Confirm:$false -ErrorAction SilentlyContinue
Remove-NetRoute -InterfaceIndex $Adapter.InterfaceIndex -Confirm:$false -ErrorAction SilentlyContinue
# Disable DHCP
Set-NetIPInterface -InterfaceIndex $Adapter.InterfaceIndex -Dhcp Disabled -ErrorAction Stop
# Set IP Address
New-NetIPAddress -InterfaceIndex $Adapter.InterfaceIndex `
-IPAddress $ipAddress `
-PrefixLength $prefixLength `
-DefaultGateway $(if (![string]::IsNullOrWhiteSpace($gateway)) { $gateway } else { $null }) `
-ErrorAction Stop | Out-Null
# Set DNS Servers
if ($dnsServers.Count -gt 0) {
Set-DnsClientServerAddress -InterfaceIndex $Adapter.InterfaceIndex `
-ServerAddresses $dnsServers `
-ErrorAction Stop
}
Write-Host "Configuration applied successfully!" -ForegroundColor Green
}
catch {
Write-Host "Error applying configuration: $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host ""
Read-Host "Press Enter to continue"
}
# Main script
try {
# Check for administrator privileges
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "This script requires administrator privileges!" -ForegroundColor Red
Read-Host "Press Enter to exit"
exit
}
do {
# Select adapter
$adapter = Get-AdapterChoice
# If null returned (PATH option was selected), continue to show menu again
if ($null -eq $adapter) {
continue
}
do {
# Show adapter information
Show-AdapterInfo -Adapter $adapter
# Show menu
Write-Host "Options:" -ForegroundColor Yellow
Write-Host "1. Set to DHCP (automatic)" -ForegroundColor White
Write-Host "2. Set Manual IP Configuration" -ForegroundColor White
Write-Host "3. Refresh Adapter Status" -ForegroundColor White
Write-Host "4. Choose Different Adapter" -ForegroundColor White
Write-Host "0. Exit" -ForegroundColor Gray
Write-Host ""
$choice = Read-Host "Select option"
switch ($choice) {
'1' {
Set-DHCPConfiguration -Adapter $adapter
}
'2' {
Set-ManualConfiguration -Adapter $adapter
}
'3' {
# Refresh - just continue the loop to redisplay info
Write-Host "Refreshing adapter status..." -ForegroundColor Yellow
Start-Sleep -Milliseconds 500
}
'4' {
break
}
'0' {
exit
}
default {
Write-Host "Invalid option!" -ForegroundColor Red
Start-Sleep -Seconds 1
}
}
} while ($choice -ne '4')
} while ($true)
}
catch {
Write-Host "An unexpected error occurred: $($_.Exception.Message)" -ForegroundColor Red
Read-Host "Press Enter to exit"
}