我确实找到了很多关于如何将 CIDR 转换为网络掩码的示例,但没有找到相反的方法(至少没有使用 PowerShell)。
因此获取数据开始工作很容易
$ActiveNic = Get-CimInstance Win32_NetworkAdapterConfiguration | where IPEnabled
[IpAddress]$MyIp = $ActiveNic.IPAddress[0]
[IpAddress]$MyMask = $ActiveNic.IPSubnet[0]
[IpAddress]$NetIp = $MyIp.Address -band $MyMask.Address
然后我需要转换掩码并开始计算
1
,我已经在下面得到了答案。
但有没有更好、更容易理解的方法呢?
我自己的看法..
function Get-NetId {
[CmdletBinding()]
param (
[Parameter()]
[IpAddress]
$IpAddress,
[Parameter()]
[IpAddress]
$IpMask
)
[IpAddress]$NetIp = $IpAddress.Address -band $IpMask.Address
[Int]$CIDR = (
(-join (
$MyMask.ToString().split('.') |
foreach {[convert]::ToString($_,2)} #convert each octet to binary
) #and join to one string
).ToCharArray() | where {$_ -eq '1'} #then only keep '1'
).Count
return $NetIp.ToString() + '/' + $CIDR
}
$ActiveNic = Get-CimInstance Win32_NetworkAdapterConfiguration | where IPEnabled
[IpAddress]$MyIp = $ActiveNic.IPAddress[0]
[IpAddress]$MyMask = $ActiveNic.IPSubnet[0]
Get-NetId -IpAddress $MyIp -IpMask $MyMask