Watching Directory for Files in PowerShell

This sample demonstrates how to process files from a source directory and then move them to another location. This script remains active always and checks for new files every 30 seconds. Currently it just moves the files, but additional processing like adding a date stamp or reading the file could be added. You could also modify the script to only run between a certain time frame if running all day is overkill.

                                        
  $sourcePath = "C:\Temp\Fol1\"
  $destinationPath = "C:\Temp\Fol2\"
  $fileMask = "*"
  $sleepDuration = 30

  #
  # Process files from one directory into another 
  #
  do
  {
   Write-host "Checking for files at"(Get-Date)"that match the mask: $($fileMask)"

   # Get files that match the mask and move to the destination
   GCI $sourcePath -Include $fileMask | %{
   
   # Log the file that was processed. Some other processing could be done here
   Write-Host "Processing File: $($_.FullName)"

   # Do the Move
   Move-Item $_.FullName -Destination $destinationPath
   }

   # Sleep the specified number of seconds
   Start-Sleep $sleepDuration
  }
  while(1 -eq 1)

                                        

The source and destination locations are configurable at the top of this script as well as the sleep duration and file mask. This type of script is useful when you have users or a process dropping files on a network share and you need to automate the handling of the files.


© 2019 Embrs.net