PowerShell脚本求助:提取时间差超10分钟的重复IP输出为空
PowerShell脚本输出为空的排查与修复
你的脚本无法输出目标IP,主要存在以下几个核心问题:
1. 哈希表数组初始化错误
当IP首次被捕获时,$ipTimestamps[$ip]的值为$null,直接使用+= , $timestamp会导致数组无法正确创建,后续时间戳无法正常添加,最终所有IP的时间戳集合为空,自然没有符合条件的结果。
2. 时间解析的文化依赖问题
使用[datetime]::ParseExact时未指定不变文化,若系统默认文化与时间格式不匹配,会导致时间戳解析失败,无法生成有效的时间对象用于计算差值。
3. 时间戳未排序(潜在逻辑漏洞)
如果文本中的时间戳并非按时间顺序出现,直接取数组首尾元素计算的差值可能不是真实的首次与末次时间差,导致筛选结果不准确。
修复后的完整脚本
# 从文本文件提取IP地址及对应时间戳 function Get-IPsWithTimestamps { param ( [string]$FilePath ) $fileContent = Get-Content -Path $FilePath -Raw # 匹配IP和yy-MM-dd HH-mm-ss格式的时间戳 $matches = [regex]::Matches($fileContent, "(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)\s+(\d{2}-\d{2}-\d{2}\s+\d{2}-\d{2}-\d{2})") $ipTimestamps = @{} foreach ($match in $matches) { $ip = $match.Groups[1].Value # 指定不变文化,避免系统文化差异导致解析失败 $timestamp = [datetime]::ParseExact($match.Groups[2].Value, "yy-MM-dd HH-mm-ss", [System.Globalization.CultureInfo]::InvariantCulture) # 初始化数组或添加时间戳 if (-not $ipTimestamps.ContainsKey($ip)) { $ipTimestamps[$ip] = @() } $ipTimestamps[$ip] += $timestamp } return $ipTimestamps } # 筛选重复出现且首次末次时间差超10分钟的IP function Get-DuplicateIPsWithTimeDifference { param ( [hashtable]$IPsWithTimestamps ) $result = @() foreach ($ip in $IPsWithTimestamps.Keys) { $timestamps = $IPsWithTimestamps[$ip] if ($timestamps.Count -ge 2) { # 对时间戳排序,确保取到最早和最晚的记录 $sortedTimestamps = $timestamps | Sort-Object $firstTimestamp = $sortedTimestamps[0] $lastTimestamp = $sortedTimestamps[-1] $timeDifference = $lastTimestamp - $firstTimestamp if ($timeDifference.TotalMinutes -gt 10) { $result += $ip } } } return $result } # 使用示例 $filePath = "C:\path\to\your\textfile.txt" $ipTimestamps = Get-IPsWithTimestamps -FilePath $filePath $targetIPs = Get-DuplicateIPsWithTimeDifference -IPsWithTimestamps $ipTimestamps # 导出结果(统一注释与代码逻辑为10分钟) $targetIPs | Out-File -FilePath "C:\path\to\output\duplicate_ips_with_time_difference.txt"
额外说明
- 修复了原脚本注释与代码逻辑不一致的问题(原注释写"超过5分钟",代码判断10分钟);
- 正则表达式保持原逻辑,若你的文本中IP与时间戳的分隔符不是空白字符,需对应调整
\s+部分。
内容的提问来源于stack exchange,提问作者ela mamo
相关产品推荐
相关产品推荐

