在文本文件中搜索然后通过电子邮件发送字符串

Search then email string in text file

每天我都需要搜索"SALES TOTAL:"之后的数字并通过电子邮件发送。我很乐意自动执行这项繁琐的任务(最好使用 PowerShell)。

有人可以帮我写一个示例脚本吗?该脚本将在 Windows Server 2012R2 with PowerShell 3.0 上 运行。

Example text file

用于搜索字符串的 Powershell 脚本:

###########################################################
$Path = "C:\temp"
$Text = "SALES TOTAL"
$PathArray = @()
$Results = "C:\temp\test.txt"

# This code snippet gets all the files in $Path that end in ".txt".
Get-ChildItem $Path -Filter "*.txt"” |
Where-Object { $_.Attributes -ne "“Directory"} |
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $Text) {
$PathArray += $_.FullName
$PathArray += $_.FullName
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}


##########################################################

然后参考这个article来规划邮件的发送(因为我不确定你会使用什么邮件客户端)。

下面的代码对我来说很完美:

$finds = Select-String -Path "file path" -Pattern "text to search" | ForEach-Object {$_.Line}

Send-MailMessage -To "email.address", -From "email.address" -Subject "subject" -body $finds[-1] -SmtpServer "smtp address" here

注意: [-1](只显示最后一行) ForEach-Object {$_.Line} 去掉文件名和行号