sireesha
sireesha

Reputation: 145

FileSystemWatcher stop working if I close the PS window it is running in

I want to continuously monitor for any new files in a folder ... if any new file, my script should pick the file and start processing it.

After Googling i found this solution and it works fine for me..

 $folder = 'G:\localexcelfiles\Logistics\logistics automation'
 $filter = '*.*'                             # <-- Takes only files that has xlsx extension


 $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
  IncludeSubdirectories = $false              
  NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
 }
 $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {

  $path = $Event.SourceEventArgs.FullPath
  $Filename = $Event.SourceEventArgs.Name
  $changeType = $Event.SourceEventArgs.ChangeType
  $timeStamp = $Event.TimeGenerated 
 }

For running this script, i am opening windows powershell ISE and running following command

  ./scriptname

this starts my script and creates a watcher to my folder.. and if i am trying to run the script again it throws an error saying "subscriber already exists"

But the problem is that ... if i am closing the powershell ISE where i ran the script ... my script is also stopping and watcher is also deleted

How to make sure that this FileSytemWatcher should run 24X7?

can this be done if my run my script using Task Scheduler?

Upvotes: 2

Views: 1625

Answers (1)

GregTank
GregTank

Reputation: 41

Call the PowerShell script from the task scheduler with the following recommended settings.

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit -noprofile
-executionpolicy bypass -file C:\YourPowerShellScript.ps1

NOTE: I added this command to a batch file then call the batch file from a the scheduled task, this is an extra step that isn't necessary but I find it is cleaner and easier to run it this way from a scheduled task..

-NoExit Stops the window from closing so it continues to run the FileSystemWatcher behind the scenes.

-NoProfile no need to load the users profile too run this script, it means it more efficient as it does not load all the users scripts that are setup in the profile.

-Executionpolicy bypass ensure that the script will be allowed to run.

Upvotes: 4

Related Questions