Change a Machine’s Subnet Mask with PowerShell Version 2

I recently worked on a project that required me to change the subnet mask on multiple servers at a remote location. The main problem was that many of the servers were still running PowerShell version 2, but luckily PowerShell remoting was enabled on all of them.

 1Invoke-Command -ComputerName (Get-Content -Path C:\MyServers.txt) {
 2    $NICs = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 'true' and DHCPEnabled = 'False'" |
 3            Where-Object {$_.ipaddress -like '192.168.0.*'}
 4
 5    foreach ($NIC in $NICs){
 6        $ip = $NIC.IPAddress -match '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
 7        [array]::Reverse($ip)
 8        $subnet = $NIC.IPSubnet -match '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$' -replace '255.255.255.0','255.255.0.0'
 9        [array]::Reverse($subnet)
10        $NIC.EnableStatic($ip, $subnet)
11    }
12
13} -Credential (Get-Credential)

This script takes into account multiple network cards and multiple IP addresses being assigned to the same network card. I discovered that the array needed to be reversed in order to assign the primary IP address back to a network card if more than one IP address was assigned to the same NIC, otherwise a secondary IP would be assigned as the primary.

The previous script filters down to network cards that have a specific range of IP addresses which are the ones connected to the LAN because many of the servers also have additional network cards that are connected to an iSCSI network and those shouldn't be modified.

The following script was used to validate that the settings were indeed changed:

1Invoke-Command -ComputerName (Get-Content -Path C:\MyServers.txt) {
2    Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 'true' and DHCPEnabled = 'False'" |
3    Where-Object {$_.ipaddress -like '192.168.0.*'} |
4    Select-Object -Property IPAddress, IPSubnet
5} -Credential (Get-Credential)

In my opinion, having to work with PowerShell version 2 is less than desirable to say the least, but even in the worst case scenario it's better than pointing and clicking in the GUI.

µ