【发布时间】:2017-04-11 03:48:39
【问题描述】:
我正在编写一个脚本来设置本地主机上的 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
【问题讨论】:
-
$IP = Read-Host -Prompt 'Please enter the Static IP Address. Format 192.168.x.x'; if($($addr=$null; [ipaddress]::TryParse($IP, [ref]$addr) -and $addr.AddressFamily -eq 'InterNetwork')) { 'Valid IPv4 address' } else { 'Not valid IPv4 address' }
标签: powershell