title: Powershell and System.IO.FileSystemWatcher
body: <p>I am new to PowerShell and I am trying to use the System.IO.FileSystemWatcher to monitor the presence of a file in a specified folder.  However, as soon as the file is detected I want to stop monitoring this folder immediately and stop the FileSystemWatcher.  The plan is to incorporate the PowerShell script into a SQL Agent to enable users to restore their own databases.  Basically I need to know the command to stop FileSystemWatcher from monitoring as soon as one file is found.  Here is the script so far.</p>
  
  <pre><code>### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
      $watcher = New-Object System.IO.FileSystemWatcher
      $watcher.Path = "C:\TriggerBatch"
      $watcher.Filter = "*.*"
      $watcher.IncludeSubdirectories = $true
      $watcher.EnableRaisingEvents = $true  
  
  ### DEFINE ACTIONS AFTER A EVENT IS DETECTED
      $action = { $path = $Event.SourceEventArgs.FullPath
                  $changeType = $Event.SourceEventArgs.ChangeType
                  $logline = "$(Get-Date), $changeType, $path"
                  Add-content "C:\log2.txt" -value $logline              
                }    
  
  ### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY  
      $created = Register-ObjectEvent $watcher Created -Action $action
  
  while ($true) {sleep 1} 
  
  ## Unregister-Event Created ??
  ##Stop-ScheduledTask ??
  </code></pre>