Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate IP address entered by user

Tags:

powershell

I am making a script to set the IP, subnet mask, gateway and DNS server address on a localhost. I have a working script but I would like to make sure that the IP addresses entered are numeric characters and within 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
like image 513
erik121 Avatar asked Apr 11 '17 03:04

erik121


1 Answers

Check this link. You can cast the given string to [ipaddress].

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

Above sample does not produce an error. If you're using an invalid 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'll receive an exception that can be caught.

like image 159
Moerwald Avatar answered Oct 06 '22 21:10

Moerwald