首页/网络/IP 与子网速查/PowerShell 快速换算网段
本包目录(177 条)
掩码与 CIDR 速算50 条
私网与特殊地址45 条子网划分方法与例题40 条IPv6 与下一代网络42 条

PowerShell 快速换算网段

Windows 环境无需安装工具:用 .NET IPAddress 与整数运算即可算出网络地址、广播地址与主机范围,适合在 Windows 运维机上批处理。

IP 与子网速查网络更新于 2026-10-12

换算函数(可直接粘贴运行)

换算函数(可直接粘贴运行)
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.159
Windows PowerShell 5.1 对 uint32 位移会先转 Int32 产生负数;用 64 位整数与除法(如上)比 -shl 更稳。

易错点

  • 直接对 0xFFFFFFFF 做位移操作得到负数,掩码整体错乱
  • 输出未固定格式时得到浮点或科学计数,地址段显示异常

数据来源与参考

  • Microsoft Learn:System.Net.IPAddress
  • RFC 4632(CIDR)

相关工具

​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌