Match IP address


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] “”

$ip_array = @{
Site1 = [ipaddress] “”, “”
Site2 = [ipaddress] “”

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

No Match



$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] ''

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

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] ‘’

$ip_hashtable = @{
Site1 = [ipaddress] ‘’
Site2 = [ipaddress] ‘’
Site3 = [ipaddress] ‘’
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

Site: Site1 (< highlighted in green)

I tried adding the below after -match but can’t figure out what I am missing.

Many Thanks,


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] ''
$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.


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