验证用户输入的IP地址

eri*_*121 4 powershell

我正在制作一个脚本来设置本地主机上的IP,子网掩码,网关和DNS服务器地址.我有一个工作脚本,但我想确保输入的IP地址是数字字符,并且每个Octet的范围在0-255之间.任何帮助,将不胜感激.

     $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
Run Code Online (Sandbox Code Playgroud)

Moe*_*ald 6

检查此链接.您可以将给定的字符串转换为[ipaddress].

PS C:\Windows\system32> [ipaddress]"192.168.1.1"
Run Code Online (Sandbox Code Playgroud)

上面的示例不会产生错误.如果您使用的是无效的IP地址:

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
Run Code Online (Sandbox Code Playgroud)

您将收到可以捕获的异常.


Nik*_*hko 6

这是结合上述两个答案的方法。
对于基本验证,此 oneliner 可以提供帮助

[bool]("text" -as [ipaddress])
Run Code Online (Sandbox Code Playgroud)

但用户可以输入类似的内容"100",它将成功验证 IP 地址0.0.0.100
这可能不是你所期望的。
所以我喜欢结合使用正则表达式和类型验证:

function IsValidIPv4Address ($ip) {
    return ($ip -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$" -and [bool]($ip -as [ipaddress]))
}
Run Code Online (Sandbox Code Playgroud)