Continuously Monitor Folder for New Files with PowerShell as a WindowsService

Recently encountered an old-school application that used a cobbled-together external service to generate reports and deliver to end-users in PDF format. Unfortunately, this service didn't have any error handling other than dropping the intended source content into a flat file in an error directory on the local disk. No monitoring, no notification, just fail and pretend it never happened. As these reports are critical to end users, I needed a way to monitor this directory for any new files and notify someone so that the report could be manually re-generated.

After some initial Googling, I decided a quick PowerShell script would be the easiest method to continuously monitor the directory and fire off a notification when a new file is found. I'm admittedly an extreme PowerShell newbie, so I'm sure there are better, cleaner ways to do this, but this works nicely and is stable enough for now until my legacy system is retired in a few months.

The below PowerShell script will instantiate an event, watch for files, send an e-mail if one is found, then go back to waiting again. Because it unregisters any existing events, it will survive a reboot or service restart and begin monitoring again without error.

  1. You will need to run Windows PowerShell ISE as an administrator to edit and test this script.

  2. You will need to set the execution policy to allow remote signed:
    Set-ExecutionPolicy RemoteSigned



# Check that WMI event subscriber isn't already running
Unregister-Event "MonitorFiles"

# Create a function that will set up the directory monitor
## Monitors every 5 seconds; change "within 5" to your desired number in seconds
Function Setup-Monitoring
{
$query = @"
Select * from __InstanceCreationEvent within 5
where targetInstance isa 'Cim_DirectoryContainsFile' AND targetInstance.GroupComponent = 'Win32_Directory.Name="c:\\\\path\\\\to\\\\directory"'
"@

Register-WmiEvent -Query $query -SourceIdentifier "MonitorFiles"

}

# Run the event setup function
Setup-Monitoring

# Create function to perform monitoring using above instantiated event
Function Start-Monitoring
{
While ($true)
{
$fileEvent = Wait-Event -SourceIdentifier "MonitorFiles"

# Get the latest object created in the monitoring directory and set the subject to include its filename
$latest = Get-ChildItem -Path "c:\\path\\to\\directory" | Sort-Object CreationTime -Descending | select $_.name -First 1
$subject = ("A report failed to generate: " + $latest)

# Set the SMTP server
$PSEmailServer = "mailserver01"
Send-MailMessage -From "[email protected]" -To "[email protected]" -CC "[email protected]" -Subject $subject -Body "Please review latest files in the error directory and manually force a report if needed: \\path\to\fileshare"

# Remove the event occurrence and go back to monitoring for another file
Remove-Event -SourceIdentifier "MonitorFiles"
}
}

# Execute the monitoring function
Start-Monitoring

Once you have the script customized and working the way you'd like, save the file to a location that the local system can access reliably (e.g. C:\scripts).

Now you'll need to download NSSM (Non-Sucking Service Manager). This utility allows you to install/edit/remove custom Windows services. I'd suggest placing it in a location that you can re-use later if you need to modify or remove the service (e.g. C:\Program Files\NSSM\).

Once you've downloaded and saved NSSM, you can now run a PowerShell command to install the service using the utility pointed at your new script. This will also require running Windows PowerShell as an administrator.
cd "C:\Program Files\NSSM"
Start-Process -FilePath .\nssm.exe -ArgumentList 'install YourServiceName "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-command "& { . C:\Scripts\ReportMonitor.ps1 }"" ' -NoNewWindow -Wait

That's it. Your service will be installed and appear under Windows Services. You can further customize the log-on as, start/stop configuration, and other service settings as you'd like from here.

Comments

Popular posts from this blog

Unprotect All Excel Sheets for All Workbooks in a Directory

ChromeOS Flow by Hexxeh Install to HDD