我有以下powershell脚本,每当新文件创建/复制到特定文件夹时,该脚本就会发送电子邮件。 我面临的唯一问题是,每当我关闭Powershell窗口时,脚本就会停止工作! 即使我从服务器注销,我也需要脚本在后台运行。我该如何实现。 我正在运行Windows Server 2012 R2
$folder = "C:\temp"
$mailserver = "172.33.33.33"
$recipient = "any@ddress.com"
$fsw = New-Object System.IO.FileSystemWatcher $folder -Property @{
IncludeSubdirectories = $true
NotifyFilter = [IO.NotifyFilters]'FileName'
}
$created = Register-ObjectEvent $fsw -EventName Created -Action {
$item = Get-Item $eventArgs.FullPath
$s = New-Object System.Security.SecureString
$anon = New-Object System.Management.Automation.PSCredential ("NT
AUTHORITY\ANONYMOUS LOGON", $s)
Send-MailMessage -To $recipient `
-From "ann@ddress.com" `
-Subject “KCC File Downloaded” `
-Body "Hi Everyone" `
-SmtpServer $mailserver `
-Credential $anon
}
答案 0 :(得分:0)
文件查看器的最佳选择是将脚本编写为Windows服务。即使您没有登录,它也可以使用,并且您可以使用服务帐户获得网络特权。 例如:https://msdn.microsoft.com/en-us/magazine/mt703436.aspx
或者您也可以将脚本放入计划任务中。 示例:https://social.technet.microsoft.com/wiki/contents/articles/38580.configure-to-run-a-powershell-script-into-task-scheduler.aspx