none
How can I have my script running in the background continuously?

    Question

  • 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
          } 
    Thursday, April 18, 2019 6:32 PM

All replies

  • Run it as a scheduled task.

    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Thursday, April 18, 2019 6:48 PM
  • The script will run once and do nothing.  You must do something to keep the script from exiting at the end of the file.


    \_(ツ)_/

    Thursday, April 18, 2019 6:58 PM
    Moderator
  • It'll continue "running" as long as the Powershell session that launched it is running.

    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Thursday, April 18, 2019 7:33 PM
  • It'll continue "running" as long as the Powershell session that launched it is running.

    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    But that only applies to running in a console session and not as a task.

    To validate a task do this:

    powershell -bypass -File script.ps1

    This is what a task does.  Also a task should be set to run at system start and not terminate.


    \_(ツ)_/


    Thursday, April 18, 2019 8:11 PM
    Moderator
  • Okay, then how about adding this at the end of the script?

    while ($true) { sleep -seconds 5 }
    Adjust the interval to suit.


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)


    Thursday, April 18, 2019 9:07 PM
  • Okay, then how about adding this at the end of the script?

    while ($true) { sleep -seconds 5 }
    Adjust the interval to suit.


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)



    Now you are cooking with code.

    \_(ツ)_/

    Thursday, April 18, 2019 9:25 PM
    Moderator
  • Run it as a scheduled task.

    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Hi Rich,

    I tried running as a task scheduler as seen in the example below. The result indicates that the job ran successfully but when I place a file in the monitored folder, no email is sent, which means the script did not run.

    C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NonInteractive -File "C:\Path\To\Your\PS1File.ps1" 

    I do not get any error. I noticed that monitor works only if I run the script while the powershell window is open/running. once I close it, the monitor stops!

    If I run  get-EventSubscriber , i do not see the process running as below:

    PS E:\KCC_FileMonitor_Job> Get-EventSubscriber

    SubscriptionId : 2
    SourceObject   : System.IO.FileSystemWatcher
    EventName       : Created
    SourceIdentifier : e05e73ec-5de4-48aa-bd88-de69d72887cf
    Action         : System.Management.Automation.PSEventJob
    HandlerDelegate :
    SupportEvent   : False
    ForwardEvent   : False


    PS E:\KCC_FileMonitor_Job>

    i need the monitor to be running continuously even after I log off from the server.

    maybe you can try the script yourself to see the behavior.

    Saturday, April 20, 2019 12:22 PM

  • i need the monitor to be running continuously 

    Did you add the "while" command as Rich suggested? Otherwise the script is just going to terminate and Powershell.exe will exit. 

    I agree with ComputerScott, the correct solution is to build a true Windows service.  

    See https://docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

    The community edition is free. https://my.visualstudio.com/downloads
    • Edited by MotoX80 Saturday, April 20, 2019 12:47 PM
    Saturday, April 20, 2019 12:43 PM
  • A few things...

    1. The help for register-objectevent indicates that this will remain *during the session*.  Once the powershell.exe process ends, this is all gone.

    2. A task could do this, but as per #1, if your powershell.exe ends, then the watcher is gone.

    I'm not interested in testing this for you, but powershell.exe also has a "-noexit" flag that you could probably pass in the task argument.  That means the powershell.exe process should not immediately exit, which appears to be exactly what you need.

    • Proposed as answer by MotoX80 Saturday, April 20, 2019 2:30 PM
    Saturday, April 20, 2019 12:54 PM
  • go with window's inbuilt solution scheduled task and configure the condition as per your requirement.
    Saturday, April 20, 2019 12:59 PM
  • Hello,

    my main issue is that the task scheduler indicates that it ran successfully but i don't that happening. I don't know why although I had other PS scripts running as tasks without any problems.

    I will try to include the the "while" command in the script and run it as a task. if not successful, then I will try to create a service as many suggested.

    Thanks.  

    Saturday, April 20, 2019 1:13 PM
  • Hello,

    my main issue is that the task scheduler indicates that it ran successfully but i don't that happening. I don't know why although I had other PS scripts running as tasks without any problems.

    I will try to include the the "while" command in the script and run it as a task. if not successful, then I will try to create a service as many suggested.

    Thanks.  

    This begs the question...  Why run it in a task at all?  Is this because you want to log on/off the computer but have this keep running?  Sure you can create a service, but if you don't have any programming experience, putting powershell.exe in some C# code is fugly.

    Remember, if you want this to run "forever", the task scheduler might seem confused...  The process is never meant to end (whether you loop it or add -noexit), therefore you probably won't get a success/error code because there's never one returned from an "infinite" script.

    Saturday, April 20, 2019 3:02 PM
  • I just ran this as a scheduled task and it worked:

    $folder = "C:\temp"
    $count = 0
    $fsw = New-Object System.IO.FileSystemWatcher $folder -Property @{
        IncludeSubdirectories = $true
        NotifyFilter = [IO.NotifyFilters]'FileName'
    }
    
    $created = Register-ObjectEvent $fsw -EventName Created -Action {
        $count++
        New-Item -Path c:\test -Name "NewFile-$count.txt"
    }
    while($true){ sleep -seconds 1 }


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Saturday, April 20, 2019 5:40 PM