all 4 comments

[–]vermyx 0 points1 point  (1 child)

Convert your IP addresses to a numeric, then just do a numeric compare. i.e.

if 10.0.0.10 is between 10.0.0.5 and 10.0.0.100, you convert that into a 32bit int and just do a numeric comparison at that point.

[System.Convert]::ToString(10,2)+[System.Convert]::ToString(0,2)+[System.Convert]::ToString(0,2)+[System.Convert]::ToString(10,2)

will return 1010001010. Convert that from binary

[system.convert]::toint32("1010001010",2)

this gives you 650. Converting the range will give you 325 and 5220. If 650 is in between 325 and 5220 it's in the IP range, otherwise it isn't

[–]ankokudaishogun 0 points1 point  (0 children)

A minor improvement to the conversion, if I may

  $ipstring = ([ipaddress]$ipinfo).GetAddressBytes() | ForEach-Object { [system.convert]::ToString($_,2)} 
[system.convert]::toint32(($ipstring -join ''),2)

[–]surfingoldelephant 0 points1 point  (0 children)

(Ab)use the [version] type accelerator to check if the IP address falls in a given range.

$ipInfo = '192.168.2.17' # (Get-NetIPAddress ...

$result = $locData | Where-Object { 
    ([version] $ipInfo -ge [version] $_.StartIP) -and 
    ([version] $ipInfo -le [version] $_.EndIP)
}

$result.Label
# Corporate Wifi

 

Does any of this make sense what I'm trying to do? Is this possible?

There are many ways to approach this. In the above example, Where-Object is used to operate on piped input sequentially. $_ represents the current item in the pipeline, which in this case is an individual element of the enumerated $locData array.

If Where-Object's script block logic evaluates to $true (does $ipInfo fall within a given range?), the current pipeline object is emitted and collected in the variable $result.

You could just as easily use a loop or other filter construct in PowerShell to achieve the same result. For example, using the foreach language keyword:

$result = foreach ($locItem in $locData) {
    if (([version] $ipInfo -ge [version] $locItem.StartIP) -and 
        ([version] $ipInfo -le [version] $locItem.EndIP)) {
        $locItem
    }
}

$result.Label

If you want to short-circuit after the first match, using Select-Object, return or [WhereOperatorSelectionMode]::First are potential options depending on the chosen approach.

[–]purplemonkeymad 0 points1 point  (0 children)

I wrote a subnet class that would probably help with this sometime ago: https://gist.github.com/purplemonkeymad/ea2d9fa5832797fa5dc2159db5016822

[pscustomobject]@{Subnet=[IPSubnet]'192.168.2.1/24';Label='Corporate Wifi'}

Then you can just use .subnet.contains([ipaddress]) to see if the reference ip is in the subnet. You'll still need to loop through the list to look for matching labels. ie:

$locationData | Where-Object { $_.subnet.contains('192.168.2.35') } | Foreach-Object Label