我有以下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
AUTHORITYANONYMOUS LOGON", $s)
Send-MailMessage -To $recipient `
-From "ann@ddress.com" `
-Subject “KCC File Downloaded” `
-Body "Hi Everyone" `
-SmtpServer $mailserver `
-Credential $anon
}
文件观察程序的最佳选择是将脚本编写为 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