0

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
  } 
  • See also my answer here which has a good foundation for your task. https://stackoverflow.com/questions/36846688/powershell-run-job-at-startup-with-admin-rights-using-scheduledjob/39378046#39378046 – Kory Gill Apr 18 '19 at 19:19
  • Can you open a command prompt from a system admin account and execute the PowerShell from there? – DBADon Apr 19 '19 at 00:27

1 Answers1

0

The best option for a file watcher is to write the script as a Windows Service. It will work even if you are not logged in and you can use a service account for network privileges. For example: https://msdn.microsoft.com/en-us/magazine/mt703436.aspx

Or you can also put the script in a scheduled task. Example: https://social.technet.microsoft.com/wiki/contents/articles/38580.configure-to-run-a-powershell-script-into-task-scheduler.aspx

Desinternauta
  • 74
  • 1
  • 8