检查Powershell中的范围

时间:2011-12-03 04:29:28

标签: powershell powershell-v2.0

我正在尝试编写一个脚本来获取计算机的IP地址,并检查它是否属于特定的IP范围。因此,例如,如果计算机的IP为192.168.0.5,则脚本将检查它是否介于192.168.0.10到192.168.0.20之间。到目前为止,我的脚本只能获取远程机器的IP,但我无法弄清楚如何检查IP是否在特定范围内。我很感激任何建议。谢谢。

6 个答案:

答案 0 :(得分:4)

让.NET完成工作可能是最简单的 - 有一个IPAddress类可以将它们解析为它们的数值以进行比较。这是一个可以放入您的配置文件的功能(或添加到模块,或者您更喜欢添加PS功能):

function IsIpAddressInRange {
param(
        [string] $ipAddress,
        [string] $fromAddress,
        [string] $toAddress
    )

    $ip = [system.net.ipaddress]::Parse($ipAddress).GetAddressBytes()
    [array]::Reverse($ip)
    $ip = [system.BitConverter]::ToUInt32($ip, 0)

    $from = [system.net.ipaddress]::Parse($fromAddress).GetAddressBytes()
    [array]::Reverse($from)
    $from = [system.BitConverter]::ToUInt32($from, 0)

    $to = [system.net.ipaddress]::Parse($toAddress).GetAddressBytes()
    [array]::Reverse($to)
    $to = [system.BitConverter]::ToUInt32($to, 0)

    $from -le $ip -and $ip -le $to
}

用法如下:

PS> IsIpAddressInRange "192.168.0.5" "192.168.0.10" "192.168.0.20"
False
PS> IsIpAddressInRange "192.168.0.15" "192.168.0.10" "192.168.0.20"
True

答案 1 :(得分:2)

对于PowerShell中的-Like运算符,这是一项简单的任务:

例如:

$ipaddress -like "192.168.1.*"

答案 2 :(得分:1)

当谷歌搜索时遇到这个,相当高的打击。只是想说至少在PowerShell 4和5中它更容易:

$range = "10.10.140.0-10.11.15.0"
$ipStart,$ipEnd = $range.Split("-")

$ipCheck = "10.10.250.255"

($ipCheck -ge $ipStart) -AND ($ipCheck -le $ipEnd)

如果您在192.168.25.0-192.168.25.255范围内提供IP 192.168.25.75,则无效

答案 3 :(得分:0)

如果掩码是255.255.255.0,那很容易 在这种情况下,你可以这样做:

$a = [ipaddress]"192.168.0.5"

10..20 -contains $a.IPAddressToString.split('.')[3]

true

对于不同的子掩码,您必须检查每个ip的octect。

答案 4 :(得分:0)

例如,要查看IP是否在192.168.1.10192.168.1.20范围内,您可以使用正则表达式和-match运算符

 $ip -match "192\.168\.1\.0?(1\d)|20"

0?允许前导0。

同样,对于任何范围,您都可以使用正则表达式。

对于非常简单的范围,请在.上使用字符串拆分并对组件进行操作。

答案 5 :(得分:0)

我写了一个小函数来做到这一点:

function Test-IpAddressInRange {
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true)][ipaddress]$from,
        [Parameter(Position = 1, Mandatory = $true)][ipaddress]$to,
        [Parameter(Position = 2, Mandatory = $true)][ipaddress]$target
    )
    $f=$from.GetAddressBytes()|%{"{0:000}" -f $_}   | & {$ofs='-';"$input"}
    $t=$to.GetAddressBytes()|%{"{0:000}" -f $_}   | & {$ofs='-';"$input"}
    $tg=$target.GetAddressBytes()|%{"{0:000}" -f $_}   | & {$ofs='-';"$input"}
    return ($f -le $tg) -and ($t -ge $tg)
}

测试结果:

PS C:\> Test-IpAddressInRange "192.168.0.1"  "192.168.0.100"  "192.168.0.1"
True
PS C:\> Test-IpAddressInRange "192.168.0.1"  "192.168.0.100"  "192.168.0.100"
True
PS C:\> Test-IpAddressInRange "192.168.90.1"  "192.168.100.100"  "192.168.101.101"
False
PS C:\>