I have the following powershell script that sends an email whenever a new file is created/copied to a specific folder. the only problem that I am facing is that whenever I close the powershell window, the script stops working! I need the script to work in the background, even when I am logged off the server. How can I achieve this. I am running 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
}