Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for a range in Powershell

I'm trying to write a script that will get an IP address of a computer and check to see whether it falls in a specific range of IPs. So for example, if the IP of the machine is 192.168.0.5, the script will check to see if it falls between the range 192.168.0.10 to 192.168.0.20. So far, my script is only able to get IPs of remote machines, but I just can't figure out how I would check if the IP is in a specific range. I'd appreciate any suggestions. Thank you.

like image 301
user1013264 Avatar asked Jul 01 '26 02:07

user1013264


2 Answers

It might be easiest to let .NET do the work - there's an IPAddress class that can parse them to their numeric values for comparison. Here's a function that you can drop into your profile (or add to a module, or however you prefer to add PS functions):

function IsIpAddressInRange {
param(
        [string] $ipAddress,
        [string] $fromAddress,
        [string] $toAddress
    )

    $ip = [system.net.ipaddress]::Parse($ipAddress).GetAddressBytes()
    [array]::Reverse($ip)
    $ip = [system.BitConverter]::ToUInt32($ip, 0)

    $from = [system.net.ipaddress]::Parse($fromAddress).GetAddressBytes()
    [array]::Reverse($from)
    $from = [system.BitConverter]::ToUInt32($from, 0)

    $to = [system.net.ipaddress]::Parse($toAddress).GetAddressBytes()
    [array]::Reverse($to)
    $to = [system.BitConverter]::ToUInt32($to, 0)

    $from -le $ip -and $ip -le $to
}

Usage looks like:

PS> IsIpAddressInRange "192.168.0.5" "192.168.0.10" "192.168.0.20"
False
PS> IsIpAddressInRange "192.168.0.15" "192.168.0.10" "192.168.0.20"
True
like image 193
E.Z. Hart Avatar answered Jul 03 '26 23:07

E.Z. Hart


i write a little function to do this:

function Test-IpAddressInRange {
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)][ipaddress]$from,
        [Parameter(Position = 1, Mandatory = $true)][ipaddress]$to,
        [Parameter(Position = 2, Mandatory = $true)][ipaddress]$target
    )
    $f=$from.GetAddressBytes()|%{"{0:000}" -f $_}   | & {$ofs='-';"$input"}
    $t=$to.GetAddressBytes()|%{"{0:000}" -f $_}   | & {$ofs='-';"$input"}
    $tg=$target.GetAddressBytes()|%{"{0:000}" -f $_}   | & {$ofs='-';"$input"}
    return ($f -le $tg) -and ($t -ge $tg)
}

test result:

PS C:\> Test-IpAddressInRange "192.168.0.1"  "192.168.0.100"  "192.168.0.1"
True
PS C:\> Test-IpAddressInRange "192.168.0.1"  "192.168.0.100"  "192.168.0.100"
True
PS C:\> Test-IpAddressInRange "192.168.90.1"  "192.168.100.100"  "192.168.101.101"
False
PS C:\>
like image 45
ncowboy Avatar answered Jul 04 '26 00:07

ncowboy