【发布时间】:2021-08-12 18:47:19
【问题描述】:
我是编程新手,Powershell,我整理了以下脚本;它解析指定文件夹中的所有电子邮件并从中提取 URL。该脚本使用正则表达式模式来识别 URL,然后将它们提取到文本文件中。提取的文本然后通过另一个命令运行,我试图删除http:// 或https:// 部分(我需要帮助解决这个问题),这些被放入另一个文本文件中,我再次从中删除重复。
我遇到的主要问题是正则表达式似乎无法正确提取网址。我得到的是类似于我在下面创建的示例:
网址是http://www.dropbox.com/3jksffpwe/asdj.exe
但我最终得到了
dropbox.com/3jksffpwe/asdj.exe
dropbox.com
drop
dropbox
脚本是
#Adjust paths to location of saved Emails
$in_files = ‘C:\temp\*.eml, *.msg’
$out_file = ‘C:\temp\Output.txt’
$Working_file = ‘C:\temp\working.txt'
$Parsed_file = ‘C:\temp\cleaned.txt'
# Removes the old output file from earlier runs.
if (Test-Path $Parsed_file) {
Remove-Item $Parsed_file
}
# regex to parse thru each email and extract the URLs to a text file
$regex = ‘([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?’
select-string -Path $in_files -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $out_file
#Parses thru the output of urls to strip out the http or https portion
Get-Content $Out_file | ForEach-Object {$_.SubString(7)} | Out-File $Working_file
#Parses thru again to remove exact duplicates
$set = @{}
Get-Content $Working_file | %{
if (!$set.Contains($_)) {
$set.Add($_, $null)
$_
}
} | Set-Content $Parsed_file
#Removes the files no longer required
Del $out_file, $Working_file
#Confirms if the email messages should be removed
$Response = Read-Host "Do you want to remove the old messages? (Y|N)"
If ($Response -eq "Y") {del *.eml, *msg}
#Opens the output file in notepad
Notepad $Parsed_file
Exit
感谢您的帮助
【问题讨论】:
-
你期望什么输出?
-
您的正则表达式中有多个匹配组
(..)。它只是返回所有匹配项。按照要求。当前的答案似乎至少在 PowerShell 3.0 上解决了这个问题
标签: regex powershell