Hey, PowerShell Guy !How Can I Change the First Two Octets of an IP Address?
An other Hey Scripting Guy translation :
How Can I Change the First Two Octets of an IP Address?
for only the IP Part I decided to use a .NET helper this time, just to do it different :
$ip = [System.Net.IPAddress]'10.10.1.2'
$b = $ip.GetAddressBytes()
"192.168.$([string]::Join('.',$b[2..3]))"
for the Complete example I also could have taken a more easy way but decided to go a bit more ...
TMTOWTDI
and used .NET for enumerating the Network Adapters and getting the IP numbers to change :
$ni = [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()
$up = $ni |? {$_.OperationalStatus -eq 'Up'}
$up | foreach {
$_.GetIPProperties().UnicastAddresses.getEnumerator() |
Foreach {
$Script:gw = $_.IPv4Mask
$_.Address
} |? {$_.AddressFamily -eq 'InterNetwork'}
} |% {$_.IPAddressToString} |? {$_ -like "10.10.*"} |% {
$ip = $_
$nics = [wmiSearcher]"Select * From Win32_NetworkAdapterConfiguration" |% {$_.get()} |? {$_.IPAddress -match "$ip"}
$nics |% {$_.EnableStatic(@($ip -replace '10.10','192.168'),@($script:gw))}
}
This looks like this pasted in the console :
[PoSH]> $ni = [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()
[PoSH]> $up = $ni |? {$_.OperationalStatus -eq 'Up'}
[PoSH]> $up | foreach {
>> $_.GetIPProperties().UnicastAddresses.getEnumerator() |
>> Foreach {
>> $Script:gw = $_.IPv4Mask
>> $_.Address
>> } |? {$_.AddressFamily -eq 'InterNetwork'}
>> } |% {$_.IPAddressToString} |? {$_ -like "10.10.*"} |% {
>> $ip = $_
>> $nics = [wmiSearcher]"Select * From Win32_NetworkAdapterConfiguration" |% {$_.get()} |? {$_.IPAddress -match "$ip"}
>> $nics |% {$_.EnableStatic(@($ip -replace '10.10','192.168'),@($script:gw))}
>> }
>>
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
[PoSH]>
This was a nice journey as the NET System.Net.NetworkInformation namespaces uses generics and PowerShell does not handle that very well (Hence the GetEnumerator() ) and also as on Vista as we have IP6 numbers, the WMI part was also a but different
I did :
$IP = $_.IPAddresses
first, to get the old array from WMI, but we get also an IP6 address back and as the EnableStatic method does not support setting this I needed to change this way of working .
(Also the Scripting Guy Article took the same --"Wrong imho what if more IP4 Numbers ? "-- way passing an array of 1 IP Address always.)
but I learned a lot and he System.Net.NetworkInformation namespace can do much more, for example :
$gp = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
$gp
$gp.GetActiveTcpConnections()
I have much more material as covered by this entry, more about this in later post
Enjoy,
Greetings /\/\o\/\/