Network configuration is crucial for system administrators managing multiple servers and devices. Automating the backup and conversion of network settings from DHCP to a static IP can save time and reduce errors. The PowerShell script below accomplishes this by backing up current network configurations and then converting DHCP-assigned IP addresses to static ones.
Here’s a detailed breakdown of how this script works and how you can utilize it effectively.
Script Overview
The PowerShell script ensures it runs with administrative privileges, checks if the backup directory exists and has the necessary write permissions, backs up current network configurations, and then converts DHCP-configured network adapters to static IP configurations.
Script Breakdown
1. Ensure Administrative Privileges
The script starts by checking if it is running with administrative privileges. Many network configuration commands require elevated permissions.
if (-not ([System.Security.Principal.WindowsPrincipal][System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "Please run this script with administrative privileges."
exit
}
2. Define Backup File Path
The script defines a backup directory and file where the network configuration will be saved.
$backupDirectory = "C:\temp"
$backupFile = Join-Path -Path $backupDirectory -ChildPath "network_config_backup.xml"
3. Ensure Backup Directory Exists
It ensures the backup directory exists or creates it if it doesn’t.
if (-not (Test-Path $backupDirectory)) {
try {
New-Item -Path $backupDirectory -ItemType Directory -Force -ErrorAction Stop
Write-Host "Backup directory created: $backupDirectory"
} catch {
Write-Host "Failed to create backup directory: $backupDirectory. $_"
exit
}
}
4. Check Write Permissions
Before proceeding, the script checks for write permissions to the backup directory by attempting to create and delete a test file.
try {
$testFile = [System.IO.Path]::Combine($backupDirectory, [System.IO.Path]::GetRandomFileName())
New-Item -Path $testFile -ItemType File -Force -ErrorAction Stop
Remove-Item -Path $testFile -Force
} catch {
Write-Host "No write permissions to backup directory: $backupDirectory. $_"
exit
}
5. Backup Current Configuration
It defines a function to backup current network configurations using Get-NetIPConfiguration and Export-Clixml.
function Backup-Configuration {
param (
[string]$FilePath
)
Get-NetIPConfiguration | Export-Clixml -Path $FilePath
}
6. Identify Connected Network Adapters
The script identifies network adapters that are currently connected.
$adapters = Get-NetAdapter | Where-Object { $_.Status -eq "Up" }
if (-not $adapters) {
Write-Host "No active network adapters found."
exit
}
7. Backup Configuration
The network configuration is backed up to the specified file.
Backup-Configuration -FilePath $backupFile
Write-Host "Network configuration backed up to $backupFile."
8. Convert DHCP to Static IP
For each adapter, the script checks if DHCP is enabled. If so, it retrieves the current DHCP settings, then converts these to static IP settings using New-NetIPAddress, Set-NetIPAddress, Set-NetRoute, and Set-DnsClientServerAddress.
foreach ($adapter in $adapters) {
Write-Host "`nChecking adapter: $($adapter.Name)"
$dhcpConfig = Get-NetIPConfiguration -InterfaceIndex $adapter.IfIndex
if (-not $dhcpConfig.IPv4Address) {
Write-Host "No IPv4 address found on adapter: $($adapter.Name)"
continue
}
$dhcpEnabled = $dhcpConfig.IPv4Address | ForEach-Object { $_.PrefixOrigin -eq "Dhcp" }
if ($dhcpEnabled -contains $true) {
$adapterFound = $true
$currentIPAddress = $dhcpConfig.IPv4Address.IPAddress
$currentSubnetMask = $dhcpConfig.IPv4Address.PrefixLength
$currentGateway = $dhcpConfig.IPv4DefaultGateway.NextHop
$currentDNSServers = $dhcpConfig.DNSServer.ServerAddresses
Write-Host "`nCurrent DHCP Configuration for adapter: $($adapter.Name)"
Write-Host "IP Address: $currentIPAddress"
Write-Host "Subnet Mask: $currentSubnetMask"
Write-Host "Gateway: $currentGateway"
Write-Host "DNS Servers: $($currentDNSServers -join ', ')"
try {
$existingIP = Get-NetIPAddress -InterfaceIndex $adapter.IfIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
if ($existingIP) {
Set-NetIPAddress -InterfaceIndex $adapter.IfIndex `
-IPAddress $currentIPAddress `
-PrefixLength $currentSubnetMask `
-AddressFamily IPv4 `
-Confirm:$false
} else {
New-NetIPAddress -InterfaceIndex $adapter.IfIndex `
-IPAddress $currentIPAddress `
-PrefixLength $currentSubnetMask `
-AddressFamily IPv4 `
-Confirm:$false
}
if ($currentGateway) {
$existingGateway = Get-NetRoute -InterfaceIndex $adapter.IfIndex -NextHop $currentGateway -ErrorAction SilentlyContinue
if ($existingGateway) {
Set-NetRoute -InterfaceIndex $adapter.IfIndex `
-NextHop $currentGateway `
-DestinationPrefix "0.0.0.0/0" `
-RouteMetric 1 `
-Confirm:$false
} else {
New-NetRoute -InterfaceIndex $adapter.IfIndex `
-NextHop $currentGateway `
-DestinationPrefix "0.0.0.0/0" `
-RouteMetric 1 `
-Confirm:$false
}
}
Set-DnsClientServerAddress -InterfaceIndex $adapter.IfIndex `
-ServerAddresses $currentDNSServers `
-Confirm:$false
$newConfig = Get-NetIPConfiguration -InterfaceIndex $adapter.IfIndex
Write-Host "`nConverted to Static IP Configuration for adapter: $($adapter.Name)"
Write-Host "IP Address: $($newConfig.IPv4Address.IPAddress)"
Write-Host "Subnet Mask: $($newConfig.IPv4Address.PrefixLength)"
Write-Host "Gateway: $($newConfig.IPv4DefaultGateway.NextHop)"
Write-Host "DNS Servers: $($newConfig.DNSServer.ServerAddresses -join ', ')"
} catch {
Write-Host "Error converting DHCP to Static on adapter: $($adapter.Name). $_"
}
} else {
Write-Host "DHCP is not enabled on adapter: $($adapter.Name)"
}
}
if (-not $adapterFound) {
Write-Host "`nNo active adapters with DHCP enabled were found."
}
Using the Script
Preparation:
1. Ensure you have administrative privileges.
Modify $backupDirectory and $backupFile paths as needed.
Execution:
2. Run the script in a PowerShell session with elevated privileges.
Observe the output to confirm successful backup and conversion.
Verification:
3. Check the backup file for accuracy.
Verify the static IP configuration using Get-NetIPConfiguration or similar commands.
Complete Script Convert DHCP IP to Static with Directory Creation
# Ensure script runs with administrative privileges
if (-not ([System.Security.Principal.WindowsPrincipal][System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "Please run this script with administrative privileges."
exit
}
# Define backup file path
$backupDirectory = "C:\temp"
$backupFile = Join-Path -Path $backupDirectory -ChildPath "network_config_backup.xml"
# Ensure the backup directory exists
if (-not (Test-Path $backupDirectory)) {
try {
New-Item -Path $backupDirectory -ItemType Directory -Force -ErrorAction Stop
Write-Host "Backup directory created: $backupDirectory"
} catch {
Write-Host "Failed to create backup directory: $backupDirectory. $_"
exit
}
}
# Check for write permissions to the backup directory
try {
$testFile = [System.IO.Path]::Combine($backupDirectory, [System.IO.Path]::GetRandomFileName())
New-Item -Path $testFile -ItemType File -Force -ErrorAction Stop
Remove-Item -Path $testFile -Force
} catch {
Write-Host "No write permissions to backup directory: $backupDirectory. $_"
exit
}
# Backup existing configuration to a file
function Backup-Configuration {
param (
[string]$FilePath
)
Get-NetIPConfiguration | Export-Clixml -Path $FilePath
}
# Get all network adapters that are currently connected
$adapters = Get-NetAdapter | Where-Object { $_.Status -eq "Up" }
if (-not $adapters) {
Write-Host "No active network adapters found."
exit
}
$adapterFound = $false
# Backup existing configuration
Backup-Configuration -FilePath $backupFile
Write-Host "Network configuration backed up to $backupFile."
foreach ($adapter in $adapters) {
Write-Host "`nChecking adapter: $($adapter.Name)"
# Retrieve the current IP configuration
$dhcpConfig = Get-NetIPConfiguration -InterfaceIndex $adapter.IfIndex
if (-not $dhcpConfig.IPv4Address) {
Write-Host "No IPv4 address found on adapter: $($adapter.Name)"
continue
}
$dhcpEnabled = $dhcpConfig.IPv4Address | ForEach-Object { $_.PrefixOrigin -eq "Dhcp" }
if ($dhcpEnabled -contains $true) {
$adapterFound = $true
# Save current IP settings
$currentIPAddress = $dhcpConfig.IPv4Address.IPAddress
$currentSubnetMask = $dhcpConfig.IPv4Address.PrefixLength
$currentGateway = $dhcpConfig.IPv4DefaultGateway.NextHop
$currentDNSServers = $dhcpConfig.DNSServer.ServerAddresses
Write-Host "`nCurrent DHCP Configuration for adapter: $($adapter.Name)"
Write-Host "IP Address: $currentIPAddress"
Write-Host "Subnet Mask: $currentSubnetMask"
Write-Host "Gateway: $currentGateway"
Write-Host "DNS Servers: $($currentDNSServers -join ', ')"
# Convert DHCP to Static IP
try {
# Check if the IP address already exists
$existingIP = Get-NetIPAddress -InterfaceIndex $adapter.IfIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
if ($existingIP) {
# If the IP exists, modify it
Set-NetIPAddress -InterfaceIndex $adapter.IfIndex `
-IPAddress $currentIPAddress `
-PrefixLength $currentSubnetMask `
-AddressFamily IPv4 `
-Confirm:$false
} else {
# Otherwise, create a new static IP
New-NetIPAddress -InterfaceIndex $adapter.IfIndex `
-IPAddress $currentIPAddress `
-PrefixLength $currentSubnetMask `
-AddressFamily IPv4 `
-Confirm:$false
}
# Set default gateway using Set-NetRoute
if ($currentGateway) {
$existingGateway = Get-NetRoute -InterfaceIndex $adapter.IfIndex -NextHop $currentGateway -ErrorAction SilentlyContinue
if ($existingGateway) {
# If the gateway exists, modify it
Set-NetRoute -InterfaceIndex $adapter.IfIndex `
-NextHop $currentGateway `
-DestinationPrefix "0.0.0.0/0" `
-RouteMetric 1 `
-Confirm:$false
} else {
# Otherwise, add a new default gateway route
New-NetRoute -InterfaceIndex $adapter.IfIndex `
-NextHop $currentGateway `
-DestinationPrefix "0.0.0.0/0" `
-RouteMetric 1 `
-Confirm:$false
}
}
# Set DNS servers
Set-DnsClientServerAddress -InterfaceIndex $adapter.IfIndex `
-ServerAddresses $currentDNSServers `
-Confirm:$false
# Retrieve new configuration to confirm the change
$newConfig = Get-NetIPConfiguration -InterfaceIndex $adapter.IfIndex
Write-Host "`nConverted to Static IP Configuration for adapter: $($adapter.Name)"
Write-Host "IP Address: $($newConfig.IPv4Address.IPAddress)"
Write-Host "Subnet Mask: $($newConfig.IPv4Address.PrefixLength)"
Write-Host "Gateway: $($newConfig.IPv4DefaultGateway.NextHop)"
Write-Host "DNS Servers: $($newConfig.DNSServer.ServerAddresses -join ', ')"
} catch {
Write-Host "Error converting DHCP to Static on adapter: $($adapter.Name). $_"
}
} else {
Write-Host "DHCP is not enabled on adapter: $($adapter.Name)"
}
}
if (-not $adapterFound) {
Write-Host "`nNo active adapters with DHCP enabled were found."
}
Conclusion
Automating the backup and configuration of network settings using PowerShell can streamline network management tasks. This script offers a reliable way to ensure network configurations are saved and easily convert DHCP settings to static IP addresses, simplifying network administration. Adapt and extend this script as needed to fit your specific network environment.