title: PowerShell File watcher to run constantly as service
body: <p>I need a bit of help with powershell scripting. I Have a file watcher.ps1 which monitors file change in sms.txt and triggers moma.ps1. So here is what I have now:</p>
  
  <pre><code>$File = "C:\Users\Ray\Desktop\sms.txt"
  $Action = 'C:\Users\Ray\Desktop\moma.ps1'
  $global:FileChanged = $false
  
  
  function Wait-FileChange {
      param(
          [string]$File,
          [string]$Action
           )
      $FilePath = Split-Path $File -Parent
      $FileName = Split-Path $File -Leaf
      $ScriptBlock = [scriptblock]::Create($Action)
  
      $Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property @{ 
          IncludeSubdirectories = $false
          EnableRaisingEvents = $true
      }
      $onChange = Register-ObjectEvent $Watcher Changed -Action {$global:FileChanged = $true}
  
      while ($global:FileChanged -eq $false){
          Start-Sleep -Milliseconds 100
      }
  
      &amp; $ScriptBlock 
      Unregister-Event -SubscriptionId $onChange.Id
  }
  
  Wait-FileChange -File $File -Action $Action
  </code></pre>
  
  <p>The problem is that the file needs to be monitored constantly every 15 seconds or so. With this script, it ends monitoring after change in file has occurred.
  Also, I would prefer if this script wold run as service, and auto start when windows does.
  Could someone guide me in right direction with this?</p>
  
  <p>New to this. Cheers</p>