One of the first things I discovered with Windows 7 was that they moved access to network adapters. I had some quick way to get to it and now I need to visit a few more screens. Today a coworker was talking about that same issue. He wanted a faster way to get to it. My response was, “I bet we can do that with Powershell”. The most common reason we end up looking at network adapters is to change ip settings to static or to DHCP. The only other things we do can be done with IPConfig. So I set out to write a little powershell that would give a computer a static IP address.
This turned out to be very simple with the Win32_NetworkAdapterConfiguration WMI object. I can use it to manage everything that was done with the GUI. The usual way we set static addresses is by first taking the dhcp address, entering it as static to the computer, then go into the dhcp server and exclude that address.
Set-NetworkStatic.ps1
$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
$IP =$NIC.IPAddress -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"
$Subnet = $NIC.IPSubnet -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"
$Gateway = $NIC.DefaultIPGateway
$DNSServers = $NIC.DNSServerSearchOrder
$Domain = $NIC.DNSDomain
$NIC.EnableStatic($IP, $Subnet)
$NIC.SetGateways($Gateway)
$NIC.SetDNSServerSearchOrder($DNSServers)
$NIC.SetDynamicDNSRegistration(“TRUE”)
$NIC.SetDNSDomain($Domain)
}
And then a second script to set it back to DHCP.
Set-NetworkDHCP.ps1
$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
$NIC.EnableDHCP()
$NIC.SetDNSServerSearchOrder()
}
