问题描述
我正在使用一个哈希表,该表使用以 CSV 格式存储的 350 万个 IP 地址的列表构建,我正在尝试使用通配符搜索该表。
CSV 是 maxmind 的 IP 列表,我使用以下代码将其转换为 Hashtable
[System.IO.File]::ReadLines("C:\temp\iptest.csv") | ForEach-Object { $data= $_.split(','); $ht = @{"geoname_id"="$($data[1])";"registered_country_geoname_id"="$($data[2])"}
$name = $($data[0])
$mainIPHhash.add($name,$ht)}
代码只是拉出 CIDR 及其对应的城市/国家/地区代码。 这运行良好,并在两分钟多一点的时间内构建了表,但我现在面临的问题是在此哈希表中搜索通配符条目。
$mainIPHhash.item("1.0.0.0/24")
Measure command reports - TotalSeconds : 0.0001542
但是如果我需要进行通配符搜索,它必须遍历哈希表寻找我喜欢的值,这需要很长时间!
$testingIP = "1.0.*"
$mainIPHhash.GetEnumerator() | Where-Object { $_.key -like $testingIP }
Measure command reports - TotalSeconds : 33.3016279
干杯
编辑:
使用正则表达式搜索,我可以将其缩短到 19 秒。但还是很慢
$findsstr = "^$(($testingIP2).split('.')[0])" +"\."+ "$(($testingIP2).split('.')[1])" +"\."
$mainIPHhash.GetEnumerator() | foreach {if($_.Key -match $findsstr){#Dostuff }}
以上取IP地址的前两个八位字节,并使用正则表达式在哈希表中找到它们。
Days : 0
Hours : 0
Minutes : 0
Seconds : 19
Milliseconds : 733
Ticks : 197339339
TotalDays : 0.000228402012731481
TotalHours : 0.00548164830555556
TotalMinutes : 0.328898898333333
TotalSeconds : 19.7339339
TotalMilliseconds : 19733.9339
解决方法
您可以获取 IP 列表并为列表执行 -like
或 -match
。两者都应该比 Where-Object
子句
$mainIPhash.Values -like '1.0.*'
$mainIPhash.Values -match '^1\.0\.'
,
其他解决方案可能是,使用组对象:
$contentcsv=import-csv "C:\temp\iptest.csv" -Header Name,geoname_id,registered_country_geoname_id |Group Name
$contentcsv | where Name -like '1.0.*'