换算函数(可直接粘贴运行)
换算函数(可直接粘贴运行)
function Get-Subnet([string]$cidr) {
$p = $cidr.Split('/'); $n = [int]$p[1]
$b = [System.Net.IPAddress]::Parse($p[0]).GetAddressBytes()
$u = [uint64]$b[0]*16777216 + [uint64]$b[1]*65536 + [uint64]$b[2]*256 + [uint64]$b[3]
$size = [math]::Pow(2, 32 - $n)
$net = [math]::Floor($u / $size) * $size
$last = $net + $size - 1
$fmt = { param($v) "$([math]::Floor($v/16777216) % 256).$([math]::Floor($v/65536) % 256).$([math]::Floor($v/256) % 256).$($v % 256)" }
[pscustomobject]@{ CIDR=$cidr; Network=(& $fmt $net); Broadcast=(& $fmt $last) }
}
Get-Subnet '192.168.1.130/27'
# Network: 192.168.1.128 Broadcast: 192.168.1.159Windows PowerShell 5.1 对 uint32 位移会先转 Int32 产生负数;用 64 位整数与除法(如上)比 -shl 更稳。