我是PowerShell的新手。我正在编写一个脚本,使用IP地址和子网掩码来计算网络ID和广播地址。我正在努力使用逻辑and。我的脚本要求用户输入IP和子网,然后将提示符转换为二进制。然后,我使用for循环执行逻辑and。然而,“.”是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)
}发布于 2020-03-07 23:39:41
我们可以使用IPV4地址及其子网掩码来计算网络ID。我们可以在这里使用-band (位和)和一个有用的.net类型IpAddress。
$ip = [ipaddress]$ipaddress
$subnet = [ipaddress]$subnetmask
$netid = [ipaddress]($ip.address -band $subnet.address)
write-host "Network id: $($netid.ipaddresstostring)"附注:可在Validating IPv4 addresses with regexp上找到用于验证IP地址的正则表达式
第一个地址是子网地址,第二个地址是brodcast地址。
发布于 2020-11-12 03:17:47
如果您恰好有作为CIDR的掩码,请使用以下命令将其转换为普通的IP掩码
$subnet = [ipaddress]([math]::pow(2, 32) -1 -bxor [math]::pow(2, (32 - $cidr))-1)https://stackoverflow.com/questions/60578612
复制相似问题