0

I have to set 3 variables depending on the IP address.

I discovered that I can use switch with -regex, but I don't know how to check if address is between two addresses.

$ip = (get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1}).ipaddress[0]
switch -regex ($ip) 
{ 
    "address 192.168.0.1-192.168.0.255" { $val = 3; } 
    "address 192.168.1.1-192.168.1.100" { $val = 1; } 
    "address 192.168.1.101-192.168.1.200" { $val = 4; } 
    "address 192.168.1.201-192.168.1.255" { $val = 5; } 
    default { exit }
}

1 Answer 1

2

I don't think regex is the best way of handling this. I'd probably do something like this

$ip = (get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1}).ipaddress.split('.')
switch ($ip) 
{ 
    {$ip[2] -eq 0} { $val = 3; } #match anything in 192.168.0.1-255
    {$ip[3] -in 1..100} { $val = 1; } 
    {$ip[3] -in 101..200} { $val = 4; } 
    {$ip[3] -in 201..255} { $val = 5; } 
    default { exit }
}
$val

If your IP blocks are different than what was provided in the example it would just be a matter of adjusting the switch conditions to match the appropriate octets

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.