2

I am new to PowerShell. I am writing a script to calculate the Network ID and Broadcast Address using the IP Address and Subnet Mask. I am struggling with the logical and. My script asks the user for the IP and Subnet, then converts the prompt to binary. I then use a for loop to perform the logical and. However, the '.' is part of the input in the for loop, so the operation does not work. Can I remove the '.' for the purpose of the operation? Some of my code is pasted below. I'm sure there is a simple solution, but I am a beginner, so any help is appreciated. Thanks!

$input = Read-Host "Would you like to calculate the Network Address? (Y for yes, N for no)"
if ($input -eq 'Y')
    {
        $ipAddress = Read-Host "Please enter your IP Address"
        $ipBin = $ipAddress -split '\.'| ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8, '0')}
        $ipBinJoin = $ipBin -join '.'
        $subnetMask = Read-Host "Please enter your Subnet Mask"
        $subnetBin= $subnetMask -split '\'| ForEach-object {[System.Convert]::ToString($_,2).PadLeft(8, '0')}
        $subnetBinJoin = $subnetBin -join '.'
        echo $ipAddress, $ipBinJoin
        echo $subnetMask, $subnetBinJoin


        for ($i = 0; $i -lt 32; $i++)
           {
                $networkIDBin = $ipBinJoin.Substring($i,1) -band $subnetBinJoin.Substring($i,1)
           }
  • You may borrow some code snippets from this script from the PowershellGallery [IP-Calc](https://www.powershellgallery.com/packages/IP-Calc/3.0.2). – Olaf Mar 07 '20 at 15:10
  • `$subnetBin= $subnetMask -split '\'` I think you missed a dot here. Should be `-split '\.'` – Manuel Batsching Mar 07 '20 at 15:38
  • Please consider selecting one of the answers as the solution to your question :) – Dennis Aug 26 '21 at 14:32

2 Answers2

6

We can calculate a network ID using IPV4 address and its subnet mask. We can use -band (Bitwise And) and a useful .net type IpAddress here.

$ip = [ipaddress]$ipaddress
$subnet = [ipaddress]$subnetmask
$netid = [ipaddress]($ip.address -band $subnet.address)
write-host "Network id: $($netid.ipaddresstostring)"

Side note: Regex to validate IP address can be found at Validating IPv4 addresses with regexp

Calculate Brodcast address https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/calculate-broadcast-address

First address is the subnet address and the second is the brodcast address.

Wasif
  • 14,755
  • 3
  • 14
  • 34
2

And if you happen to have the mask as CIDR, convert it to a plain IP-mask using

$subnet = [ipaddress]([math]::pow(2, 32) -1 -bxor [math]::pow(2, (32 - $cidr))-1)
Dennis
  • 871
  • 9
  • 29