Check the IP address entered by the user

I am creating a script to set the IP address, subnet mask, gateway and DNS server address on the local host. I have a working script, but I would like to make sure that the IP addresses entered are numeric characters and in the range 0-255 for each octet. Any help would be appreciated.

     $IP = Read-Host -Prompt 'Please enter the Static IP Address.  Format 192.168.x.x'
                $MaskBits = 24 # This means subnet mask = 255.255.255.0
                $Gateway = Read-Host -Prompt 'Please enter the defaut gateway IP Address.  Format 192.168.x.x'
                $Dns = Read-Host -Prompt 'Please enter the DNS IP Address.  Format 192.168.x.x'
                $IPType = "IPv4"

            # Retrieve the network adapter that you want to configure
               $adapter = Get-NetAdapter | ? {$_.Status -eq "up"}

           # Remove any existing IP, gateway from our ipv4 adapter
 If (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) {
    $adapter | Remove-NetIPAddress -AddressFamily $IPType -Confirm:$false
}

If (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) {
    $adapter | Remove-NetRoute -AddressFamily $IPType -Confirm:$false
}

 # Configure the IP address and default gateway
$adapter | New-NetIPAddress `
    -AddressFamily $IPType `
    -IPAddress $IP `
    -PrefixLength $MaskBits `
    -DefaultGateway $Gateway

# Configure the DNS client server IP addresses
$adapter | Set-DnsClientServerAddress -ServerAddresses $DNS
+4
source share
3 answers

Check out the link. You can pass this string to [ipaddress].

PS C:\Windows\system32> [ipaddress]"192.168.1.1"

No error occurs over the sample. If you are using the wrong IP address:

PS C:\Windows\system32> [ipaddress]"260.0.0.1"
Cannot convert value "260.0.0.1" to type "System.Net.IPAddress". Error: "An 
invalid IP address was specified."
At line:1 char:1
+ [ipaddress]"260.0.0.1"
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastParseTargetInvocation

You will get an exception that can be caught.

+6
source

Keep in mind that if you use typecasting, for example, [IPAddress] 192.168.1.1to check, then there may be a case that the conversion is incorrect.

: [IPAddress] 192 192.0.0.0. , 192 IP-.

0

Use regular expressions

$ipRegEx="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
if($ip -notmatch $ipRegEx)
{
   #error code
}

You can search the Internet for regular expressions and examples for IP. Just keep in mind that powershell is built on top of .NET, so when searching and reading for regular expressions, focus on .NET or C #. For example this .

Update As stated after the comments, the regular expression is incorrect, but it was published as an example of validating the expressions. An alternative could be((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

-1
source

Source: https://habr.com/ru/post/1674537/


All Articles