PowerShell: Understanding File Monitoring
Powershell PowershellThis PowerShell script is designed to monitor a specified folder for the creation of new files. It utilizes the FileSystemWatcher
class to trigger actions based on file events and logs important information to a custom event log. Let’s break down its core structure and functionality.
1. Configuration Section
At the beginning of the script, essential variables are defined:
$FolderPath
: The path to the folder that will be monitored.$WatcherID
: A unique identifier for the event watcher.$ScriptToRun
: The PowerShell script that will be executed when a new file is detected.
$FolderPath = "C:\Temp"
$WatcherID = "FileCreatedWatcher"
$ScriptToRun = ".\myactionscript.ps1"
2. Event Log Creation
The script checks for the existence of a custom event log (MyApp-Log). If it doesn’t exist, the script creates it and logs an informational message. This is crucial for tracking events related to the file monitoring process.
$logName = "MyApp-Log"
$logExists = Get-EventLog -List | Where-Object {$_.Log -eq $logName}
if ($logExists -eq $null) {
New-EventLog -LogName $logName -Source "MyApp-Monitoring"
Write-EventLog -LogName $logName -Source "MyApp-Monitoring" -EntryType Information -EventId 1 -Message "Event log '$logName' has been created."
} else {
Write-Host "Event log '$logName' already exists."
}
3. Folder Existence Check
The script verifies that the specified folder ($FolderPath
) exists. If not, it logs a critical error and exits to prevent further execution.
if (!(Test-Path $FolderPath)) {
Write-Host "Error: The folder path '$FolderPath' does not exist." -ForegroundColor Red
Write-EventLog -LogName MyApp-Log -Source MyApp-Monitoring -EntryType Critical -EventId 661 -Message "$FolderPath does not exist, or is inaccessible!"
exit
}
4. Defining the Action for New Files
An action is defined using a script block ($Action
) that specifies what to do when a new file is created. It takes parameters for the event source and event arguments, extracts the new file’s path, and executes the specified script after a brief pause.
$Action = {
param($Source, $EventArgs)
$NewFilePath = $EventArgs.Name
$Ctime = Get-date -format "HH:mm"
Write-Host " New file created at $CTime " -BackgroundColor Green -ForegroundColor Yellow -NoNewline
Write-Host " $NewFilePath " -BackgroundColor Yellow -ForegroundColor Blue
start-sleep -Seconds 5
& $event.MessageData.ScriptPath
Clear-Host
Write-Host " Monitoring for new files in " -BackgroundColor Blue -ForegroundColor Yellow -NoNewline
Write-Host " $($event.MessageData.Path) " -BackgroundColor Yellow -ForegroundColor DarkBlue
}
5. Setting Up the FileSystemWatcher
The FileSystemWatcher
object is created to monitor the specified folder. It is configured to watch for newly created files and to raise events accordingly.
$Watcher = New-Object System.IO.FileSystemWatcher
$Watcher.Path = $FolderPath
$Watcher.Filter = "*.*"
$Watcher.IncludeSubdirectories = $false
$Watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName
$MessageData = @{
Path = $FolderPath
ScriptPath = $ScriptToRun
}
Register-ObjectEvent -InputObject $Watcher -EventName Created -SourceIdentifier $WatcherID -Action $Action -MessageData $MessageData
$Watcher.EnableRaisingEvents = $true
6. Monitoring Loop
The script enters a monitoring loop, waiting for file creation events. It logs the start of monitoring and continuously checks for new files.
Write-EventLog -LogName MyApp-Log -Source MyApp-Monitoring -EntryType Information -EventId 667 -Message "Folder Monitoring started for $FolderPath."
Wait-Event -SourceIdentifier $WatcherID
7. Cleanup and Shutdown
Finally, the script ensures proper cleanup by unregistering the event and disposing of the watcher object. It logs a message indicating that monitoring has stopped.
finally {
Unregister-Event -SourceIdentifier $WatcherID -ErrorAction SilentlyContinue
if ($Watcher) { $Watcher.Dispose() }
Write-host "Folder Watcher stopped." -ForegroundColor Magenta
Write-EventLog -LogName MyApp-Log -Source MyApp-Monitoring -EntryType Warning -EventId 668 -Message "Folder Monitoring stopped for $FolderPath."
}
Conclusion
This PowerShell script effectively monitors a folder for new file creations, executes a specified script upon detection, and maintains a log of events. Its modular structure allows for easy modifications and scalability for more complex monitoring scenarios.