我想创建一个脚本来监视计算机中的特定文件夹,并且如果创建了新文件,则通过电子邮件发送此文件。我发现:
$action = {
$WatchFolder = "C:\Users\..."
$To = "[email protected]"
$From = "[email protected]"
$Subject = "New File"
$Body = "New file has been created"
$SMTPServer = "xxx.abc.fr"
$Files = (Get-ChildItem $WatchFolder).FullName
if ($Files) {
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Files
Remove-Item $Files
}
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}
当然它不起作用。如你所见,我是 powershell 新手。有人能帮我吗?谢谢你们
答案1
我做了一些修改,现在可以正常工作了。解决方案:
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\..."
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
### MAIL SETUP
$To = "[email protected]"
$From = "[email protected]"
$Subject = "Exemple"
$Body = "Exemple"
$SMTPServer = "abc.xyz.fr"
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $path
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}
感谢您的贡献