发送电子邮件的脚本

时间:2020-10-12 11:21:04

标签: powershell shell scripting

我在网上找到了一个脚本,该脚本的工作非常简单-按下触发器后,会将电子邮件发送到指定的地址。

在下面的示例中,脚本应该扫描我为触发器指定的路径: #task ,然后希望它发送带有 #td之后文本的电子邮件

应该是正确的,但是当我运行它时,什么也没发生-我在做什么错? 我在 powershell 中收到以下消息:

enter image description here

# Unregister-Event FileCreated
Unregister-Event FileChanged

# Email-settings
$loginuser = 'xxx@gmail.com'
$loginpassword = 'password;'
$smtpserver = 'smtp.gmail.com'
$smtpport = 587
$sendfrom = 'xxx@gmail.com'
$sendto = 'add.task.9270372.1523940684@todoist.net'

# Folder-settings
$folder = 'D:\Google Drive\Other\Nirvana' # Enter the root path you want to monitor.
$filter = '*.*'  # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }

# Trigger-settings
$trigger = '#task'
$lookfor = '#td'
$replaceto = '#intasklist'

Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    $fileContent = (Get-Content $folder$name)
#    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
   if ($fileContent -match $trigger) {
    $fileContent | Select-String -Pattern ".*$($lookfor)" -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $secpasswd = ConvertTo-SecureString $loginpassword -AsPlainText -Force; $cred = New-Object System.Management.Automation.PSCredential ($loginuser, $secpasswd); Send-MailMessage -To $sendto -From $sendfrom  -Subject $_.Value -Body $name -SmtpServer $smtpserver -Port $smtpport -Credential $cred -UseSsl
    $fileContent | ForEach-Object { $_ -replace $lookfor, $replaceto -replace " $($trigger)", '' -replace $trigger, '' } | Set-Content $folder$name }
    }}

# To stop the monitoring, run the following commands:
# Unregister-Event FileChanged

0 个答案:

没有答案