gpt4 book ai didi

powershell - 验证用户输入的 IP 地址

转载 作者:行者123 更新时间:2023-12-05 00:52:06 24 4
gpt4 key购买 nike

我正在制作一个脚本来在本地主机上设置 IP、子网掩码、网关和 DNS 服务器地址。我有一个工作脚本,但我想确保输入的 IP 地址是数字字符,并且每个八位字节的范围在 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

最佳答案

检查这个 link .您可以将给定的字符串转换为 [ipaddress] .

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

以上示例不会产生错误。如果您使用了无效的 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

您将收到一个可以被捕获的异常。

关于powershell - 验证用户输入的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43336422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com