PowerShell--使用 IP 地址和子网掩码计算网络 ID

标签 powershell

我是 PowerShell 的新手。我正在编写一个脚本来使用 IP 地址和子网掩码计算网络 ID 和广播地址。我正在为逻辑与而苦苦挣扎。我的脚本要求用户提供 IP 和子网,然后将提示转换为二进制。然后我使用 for 循环来执行逻辑与。但是,那 '。'是 for 循环中输入的一部分,因此操作不起作用。我可以删除“。”吗?为了手术的目的?下面粘贴了我的一些代码。我确定有一个简单的解决方案,但我是初学者,因此不胜感激。谢谢!

$input = Read-Host "Would you like to calculate the Network Address? (Y for yes, N for no)"
if ($input -eq 'Y')
    {
        $ipAddress = Read-Host "Please enter your IP Address"
        $ipBin = $ipAddress -split '\.'| ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8, '0')}
        $ipBinJoin = $ipBin -join '.'
        $subnetMask = Read-Host "Please enter your Subnet Mask"
        $subnetBin= $subnetMask -split '\'| ForEach-object {[System.Convert]::ToString($_,2).PadLeft(8, '0')}
        $subnetBinJoin = $subnetBin -join '.'
        echo $ipAddress, $ipBinJoin
        echo $subnetMask, $subnetBinJoin


        for ($i = 0; $i -lt 32; $i++)
           {
                $networkIDBin = $ipBinJoin.Substring($i,1) -band $subnetBinJoin.Substring($i,1)
           }

最佳答案

我们可以使用 IPV4 地址及其子网掩码计算网络 ID。我们可以在这里使用 -band(按位与)和一个有用的 .net 类型 IpAddress。

$ip = [ipaddress]$ipaddress
$subnet = [ipaddress]$subnetmask
$netid = [ipaddress]($ip.address -band $subnet.address)
write-host "Network id: $($netid.ipaddresstostring)"

旁注:验证 IP 地址的正则表达式可在 Validating IPv4 addresses with regexp 找到

计算广播地址https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/calculate-broadcast-address

第一个地址是子网地址,第二个是广播地址。

关于PowerShell--使用 IP 地址和子网掩码计算网络 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578612/

相关文章:

powershell - 基本循环帮助 - Powershell

powershell - 当脚本设置为 “Run As Admin”时,有没有办法在Powershell中映射本地驱动器?

powershell - Powershell想要通过开关创建属性并返回到csv

powershell - 禁止显示 Azure Stop-AzureRMVM cmdlet 警告消息框

powershell - 在 Windows 文件共享上设置权限

powershell:如何使用 ls dirA,dirB -rec |组文件名,版本信息。产品版本 |英尺-自动...?

Powershell 多维数组

json - 使用 PowerShell 如何在具有注释的 json 文件中替换和保存值

powershell - 将字符串参数发送到 Start-Job 脚本 block

powershell - 在 powershell 中,使用 export-csv cmdlet,我的整数被引号封装,知道为什么吗?