title: Script listening to folder event Powershell
body: <p>I am having problem with a Powershell script. What I am doing in the following lines of code is hopefully clear by STEPS (1)-(4):</p>
  
  <pre><code># STEP (1) Create listener on folder where outputfile.pdf file will be created 
  #         (folder here is `$folder`).
  
  # STEP (2) Wait for new .pdf file to be created.
  
  # STEP (3) When file is created, send mail and print.
  
  # STEP (4) Unsubscribe listener.
  
  
  $folder = 'X:\foldername'
  $filter = '*.*'                             # &lt;-- set this according to your requirements
  
  # STEP (1)
  
  $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
   IncludeSubdirectories = $false             # &lt;-- set this according to your requirements
   NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
  }
  
  # Run python script, removing existing .pdf-files.
  Write-Host "Running PS-script..."
  start-process runrisk.bat -workingdirectory "H:\FX\"
  
  # STEP (2)
  
  $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
   $path = $Event.SourceEventArgs.FullPath
   $name = $Event.SourceEventArgs.Name
   $changeType = $Event.SourceEventArgs.ChangeType
   $timeStamp = $Event.TimeGenerated
  
   # STEP (3)    
  
   # Call sendMail.ps1 to send mail confirmation
   invoke-expression -Command .\sendMail.ps1
   Write-Host "The file '$name' was $changeType at $timeStamp `r"
  
   # Print file
   start-process outputfile.pdf -workingdirectory "X:\folder1" -verb Print
  
   # STEP (4)
   # unregister current subscription
    Unregister-Event -SourceIdentifier FileCreated
  
  }
  </code></pre>
  
  <p>I have built an .exe-file around this script. If I run this .ps1 file directly from PowerShell, everything works as  one would expect: (1) Create listener onto folder, (2) delete old .pdf-file and wait for new .pdf-file to be created, (3) print and send mail on creation-event, (4) unsubscribe listener.</p>
  
  <p>When trying to run the .exe file, or when e.g. running the ps1-file through Windows Task Scheduler, it seems to only run until STEP (2), i.e. it seems as though no listener is created, and hence nothing happens when the bat-file creating .pdf-file is finished. It just flashes some cmd-window and that's it.</p>
  
  <p>Any thoughts would be very much grateful!</p>
  
  <p>Thanks,
  Niklas</p>