我有一个 PowerShell 脚本,用于监视文件夹以检测新 PDF 文件的创建并自动触发打印它们的操作。但是,我想避免脚本连续运行,并且我无法使用任务计划程序,因为服务器每天都会重新启动,这会导致所有计划任务被删除。
我正在寻找一种解决方案,允许脚本仅在创建新的 PDF 文件时自动运行,而不是连续运行。我还需要一种替代方案,可以在服务器每天重新启动后继续存在,并且可以自动触发脚本,而无需手动干预或持续监督。
考虑 System.IO.FileSystemWatcher 对象。
Noah Peltier 在 gist.github.com
上提供了一个很好的示例$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = "C:\temp"
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action {
$Object = "{0} was {1} at {2}" -f $Event.SourceEventArgs.FullPath,
$Event.SourceEventArgs.ChangeType,
$Event.TimeGenerated
$Event.SourceEventArgs.FullPath
############################ Get the last file in the directory and pull its contents
$filepath = "C:\temp"
$filename = (get-content $filepath | sort CreationTime -Descending | select -last 1).Name
$Join = Join-Path -path $filepath -ChildPath $filename
$content = Get-Content -Raw $join | out-string
############################ Send the message
$EmailParams = @{
credential = Import-CliXml -Path 'C:\temp\cred.xml' # this needs to be stored prior with "Get-Credential | Export-CliXml -Path C:\path\cred.xml"
From = "[email protected]"
To = "[email protected]"
Subject = $Object
Body = $content
SMTPServer = "smtp.gmail.com"
Port = "587"
}
Send-MailMessage @EmailParams -UseSsl
}