如何通过PowerShell提取IP地址并单独保存至TXT文件?
问题:提取PowerShell脚本结果中的IP地址并保存到TXT文件
我的PowerShell脚本如下:
$geturl = Invoke-WebRequest "https://www.sample.com/" $li=$geturl.ParsedHtml.body.getElementsByTagName('li') | Where {$_.getAttributeNode('class').Value -eq 'col-md-6'} $ip = $li | select OuterText
脚本返回结果:
outerText --------- 179.60.147.106 (1986 reports from 281 distinct users) 195.226.194.242 (1000 reports from 274 distinct users) 195.226.194.142 (957 reports from 260 distinct users) 61.177.173.50 (857 reports from 201 distinct users) 61.177.172.114 (708 reports from 200 distinct users) 61.177.173.36 (869 reports from 199 distinct users) 61.177.173.53 (847 reports from 198 distinct users) 61.177.173.49 (818 reports from 198 distinct users) 39.109.86.40 (287 reports from 197 distinct users) 61.177.172.124 (786 reports from 194 distinct users)
我希望仅将上述结果中的IP地址保存到TXT文件中,请问是否可以实现?若可以,该如何操作?
解决方案
完全可以实现,通过正则表达式匹配IPv4地址即可提取目标内容,再写入TXT文件。以下是两种实现方式:
方式一:直接修改原有脚本
$geturl = Invoke-WebRequest "https://www.sample.com/" $li = $geturl.ParsedHtml.body.getElementsByTagName('li') | Where {$_.getAttributeNode('class').Value -eq 'col-md-6'} # 遍历每个li元素,用正则提取IP $ipAddresses = $li | ForEach-Object { if ($_.OuterText -match '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b') { $matches[0] } } # 将IP写入指定路径的TXT文件,替换为你的实际保存路径 $ipAddresses | Out-File -FilePath "C:\your\save\path\ip_list.txt" -Encoding UTF8
方式二:基于已有$ip变量处理
如果不想改动原有脚本逻辑,可在得到$ip变量后单独处理:
# 假设已通过原脚本得到$ip变量 $ipAddresses = $ip.outerText | ForEach-Object { if ($_ -match '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b') { $matches[0] } } # 写入当前目录下的ip_list.txt文件 $ipAddresses | Out-File -FilePath "ip_list.txt" -Encoding UTF8
关键说明:
- 正则表达式
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b用于匹配标准IPv4地址,确保只提取IP部分; Out-File命令支持指定文件路径和编码,根据需求调整即可。
内容的提问来源于stack exchange,提问作者BatchProblem123
相关产品推荐
相关产品推荐

