Categories
powershell

ipcalc in powershell

Last day I wrote how to do it in AIX or Linux ip calc with ifconfig

It isn’t that different in PowerShell, the fun is to the calculation yourself. For translating 0.0.0.0 in 0, we can use [IPADDRESS].

Let’s try‚Ķ

$ip = [IPADDRESS](
(Get-NetIPAddress -AddressFamily "IPv4" -InterfaceAlias "Ethernet*").
ipaddress)

$prefix = (
Get-NetIPAddress -AddressFamily "IPv4" -InterfaceAlias "Ethernet*").
prefixlength

The length and the ip of the current interface. In my case I have only one

PS> $ip
Address : 1677830336
AddressFamily : InterNetwork
IPAddressToString : 192.168.1.100
PS> $prefix
24

with a prefix length of 24, we need a netmask of 24 bits

11111111.11111111.11111111.00000000

which is

11111111.11111111.11111111.11111111 --> 2^32-1
-
11111111 --> 2^(32-24)-1

to do the math

$netmask=[IPADDRESS]([Math]::Pow(2,32)-[Math]::Pow(2,32-$prefix))
IPAddressToString : 255.255.255.0

let’s bitand

$netid = [IPADDRESS]($ip.Address -band $netmask.address)
IPAddressToString : 192.168.1.0

By Laurent Schneider

Oracle Certified Master

Leave a Reply

Your email address will not be published.