top of page

How To Set Static IP Using PowerShell in Windows

  • Mohan Sekar
  • Nov 15, 2017
  • 1 min read

PowerShell - Configure Static IP Address in Windows

<# .Synopsis Update the static IP address one to another .DESCRIPTION This Script is used to update the static IP address one to another .EXAMPLE Set-StaticIP -NewIPaddress '10.77.8.151' -NewSubnetmask '255.255.255.0' -NewDefaultgateway '10.77.8.1' -NewPreferredDNS '8.8.8.8' To update the static IP address to new VLAN. (i.e., 10.77.8.xxx) .EXAMPLE Set-StaticIP -NewIPaddress '10.77.3.151' -NewSubnetmask '255.255.254.0' -NewDefaultgateway '10.77.2.1' -NewPreferredDNS '10.77.3.2' -NewAlternateDNS '10.77.3.1' To update the static IP address to old VLAN. (i.e., 10.77.3.xxx) #> function Set-StaticIP { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] $NewIPaddress, [Parameter(Mandatory=$true)] $NewSubnetmask, [Parameter(Mandatory=$true)] $NewDefaultgateway, [Parameter(Mandatory=$true)] $NewPreferredDNS, $NewAlternateDNS ) Begin { $OldInfo = Get-WmiObject -ComputerName . Win32_NetworkAdapterConfiguration | Where-Object { $_.IPAddress -ne $null -and $_.DefaultIPGateway -ne $null } $ServerName = $OldInfo.DNSHostName $OldIPaddress = $OldInfo.IPAddress[0] $OldSubnetmask = $OldInfo.IpSubnet[0] $OldDefaultgateway = $OldInfo.DefaultIPGateway $OldPreferredDNS = $OldInfo.DNSServerSearchOrder[0] $OldAlternateDNS = $OldInfo.DNSServerSearchOrder[1] } Process { try { if ($NewAlternateDNS) { $NewDNSServer=$NewPreferredDNS,$NewAlternateDNS } else { $NewDNSServer=$NewPreferredDNS } $wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'" | Where-Object -FilterScript { $_.DefaultIPGateway -ne $null } $wmi.EnableStatic($NewIPaddress, $NewSubnetmask) $wmi.SetGateways($NewDefaultgateway, 1) $wmi.SetDNSServerSearchOrder($NewDNSServer) Write-Host "IP Address and DNS Update: SUCCESS" -ForegroundColor Green } catch { Write-Host $_.Exception Write-Host "IP Address and DNS Update: FAILED" -ForegroundColor Red Write-Host "Reverting back to the old IP and DNS" if ($OldAlternateDNS) { $OldDNSServer=$OldPreferredDNS,$OldAlternateDNS } else { $OldDNSServer=$NewPreferredDNS } $wmi.EnableStatic($OldIPaddress, $OldSubnetmask) $wmi.SetGateways($OldDefaultgateway, 1) $wmi.SetDNSServerSearchOrder($OldDNSServer) } } End { Write-Host "Set Static IP Address PowerShell Script Processed on $ServerName" -ForegroundColor DarkYellow Write-Warning "Please ensure VM Network Adopter Connection should be mapped to correct one" } }

Comments


RECENT POSTS:
SEARCH BY TAGS:

© 2023 by NOMAD ON THE ROAD. Proudly created with Wix.com

  • b-facebook
  • Twitter Round
  • Instagram Black Round
bottom of page