我在excel电子表格中有一系列子网范围
我实际上需要扩展每个范围以包括单个主机地址,然后列出它们。即
直到范围中的最后一个数字完成。
本质上,从电子表格或txt文件中读取IP地址列表(格式= 10.0.0.1-10
),列出低位和高位之间的所有值以获取完整范围的主机地址,但是这样做是为了多个范围并导出到文本文件或CSV。
我已经尝试过了,但是只有当我在subnet.txt中输入较小的数字而在subnet2.txt中输入最大的数字时,它才起作用,但是,每个文件只允许一个数字,因此它不能扩展,即不能简单地在一个文件中列出所有IP范围。并且必须手动在其中添加网络地址。
$x = Get-Content "H:\subnet.txt"
$y = Get-Content "H:\subnet2.txt"
$computers = $x..$y | foreach { "10.0.0.$_" }
$computers
答案 0 :(得分:0)
如果输入形式为10.0.0.1-10
,则可以使用-split
正则表达式运算符将其分为3个变量部分:
$string = '10.0.0.1-10'
# split on the last '.' (ie. the dot followed by '1-10')
$prefix,$range = $string -split '\.(?=\d+-\d+)'
# split the range (1-10) into 1 and 10
$from,$to = $range -split '-'
$from..$to | ForEach-Object { "$prefix.$_"}
我建议定义一个过滤器,以便您可以轻松地通过管道输入内容:
filter Expand-IPRange {
if(($string = $_) -notmatch '^(?:\d{1,3}\.){3}\d{1,3}-\d{1,3}$')){
Write-Error "invalid ip range notation: $_"
}
$prefix,$range = $string -split '\.(?=\d+-\d+)'
$from,$to = $range -split '-'
$from..$to | ForEach-Object {
"$prefix.$_"
}
}
Get-Content ipranges.txt |Expand-IPRange |Set-Content ipaddresses.txt
答案 1 :(得分:0)
您提到Excel,所以我认为您的数据可以CSV格式导出,以下解决方案基于此格式:
# Read the ranges into an array of custom objects with .From and .To properties
$ranges=@'
From,To
10.0.0.1,10.0.0.2
10.1.1.1,10.1.1.3
'@ | ConvertFrom-Csv # IRL you'd use Import-Csv with a file.
# Loop over all ranges
foreach ($range in $ranges) {
# Extract the first 3 components, assumed to be the same in
# both the .From and .To values, e.g., '10.0.0'
$first3Components = $range.From -replace '\.[^.]+$'
# Extract the last components, which mark the range endpoints, as numbers.
# E.g., 1 and 2
$fromLastComponent = [int] ($range.From -split '\.')[-1]
$toLastComponent = [int] ($range.To -split '\.')[-1]
# Loop between the range endpoints.
foreach ($lastComponent in $fromLastComponent..$toLastComponent) {
"$first3Components.$lastComponent"
}
}
以上结果:
10.0.0.1
10.0.0.2
10.1.1.1
10.1.1.2
10.1.1.3