Match IP address

Hi,

I wonder if someone could help, I am trying to create an array containing multiple sites and if the computer IP matches IP, I want it to list the site but I’m missing something. Code below.

$myIP =[ipaddress] “192.168.2.2”

$ip_array = @{
Site1 = [ipaddress] “192.168.1.1”, “192.168.1.4”
Site2 = [ipaddress] “192.168.2.2”
}

foreach ($IP in $ip_array){
if ($myIP -match $IP){Write-output $IP.Keys } else {Write-host “No Match” -ForegroundColor Red}}

Result::
No Match

Thanks,

Mac

$ip_array is technically a hash table and not an array. GetEnumerator will allow you to loop through the key/value pairs in the hash table. Then, since the values may be an array (Site1 has an array of IP addresses for the value), use -contains to see if the value contains the address you are searching for.

$myIP = [ipaddress] '192.168.2.2'

$ip_hashtable = @{
    Site1 = [ipaddress] '192.168.1.1', '192.168.1.4'
    Site2 = [ipaddress] '192.168.2.2'
}
foreach ($IP in $ip_hashtable.GetEnumerator()) {
    if ($IP.Value -contains $myIP) { Write-Output $IP.Key } else { Write-Host 'No Match' -ForegroundColor Red }
}
3 Likes

Thanks @darwin-reiswig that worked like a treat. It also started listing all the sites where the IP address did not match so I added a bit more code so It could only match the first 3 octets

$myIP = [ipaddress] ‘192.168.2.20’

$ip_hashtable = @{
Site1 = [ipaddress] ‘192.168.1.1’
Site2 = [ipaddress] ‘192.168.2.1’
Site3 = [ipaddress] ‘192.168.3.1’
}
foreach ($IP in $ip_hashtable.GetEnumerator()){
if ($IP.Value -contains $myIP -and $IP.Value -match ‘(\d{1,3}.\d{1,3}.\d{1,3}.)’ ) { $found = $IP.Key } else { Write-Output $IP.Key}
}
Write-Host “Site: $found” -ForegroundColor Green

Result:
Site3
Site1
Site2
Site: Site1 (< highlighted in green)

I tried adding the below after -match but can’t figure out what I am missing.
'(\d{1,3}).(\d{1,3}).(\d{1,3})
“\d{1,3}.\d{1,3}.\d{1,3}”
(\d{1,3}.\d{1,3}.\d{1,3}.)

Many Thanks,

Mac

If your goal is to match the first 3 octets of the IP address, rather than the entire IP address, that does change the requirements.

Here’s how I would approach it. I would manipulate the value of $myIP to replace the .20 with .1, and then the rest of the code would work as written. Something like this should work:

$myIP = [ipaddress] '192.168.2.20'
$IpSplit = $myIP.IPAddressToString.split('.')
[ipaddress]$IpRange = "$($IpSplit[0]).$($IpSplit[1]).$($IpSplit[2]).1"

Then $IpRange would match one of the items in the hash table.

If this isn’t what you’re ultimately needing, though, some more information about your final goal for this code would help.

2 Likes

BTW, it does make your posts more readable if your code is formatted as code. See under the gear icon the preformatted option.

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.