Last active
April 20, 2020 09:50
-
-
Save mziyabo/aa686a0c1d9dd22d1d9ce4be9ad080a0 to your computer and use it in GitHub Desktop.
PowerShell File Watcher w/o PowerShell Eventing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Param | |
( | |
[Parameter()] | |
[string]$FileDirectory, | |
[Parameter(Mandatory=$true)] | |
[string]$FilePattern, | |
[Parameter(Mandatory=$true)] | |
[float]$PollingIntervalMin, | |
[Parameter()] | |
[scriptblock]$FileFoundAction | |
) | |
function PollFileDirectory() | |
{ | |
Write-Host 'Polling Directory: $FileDirectory at $PollingIntervalMin minute Intervals.' -ForegroundColor Cyan; | |
Write-Host 'Target Pattern: ' $FilePattern -ForegroundColor Cyan; | |
$existingFileString = [string]::Empty; | |
#Poll Directory Indefinitely | |
while ($true) | |
{ | |
#Wait for Duration equal to PollingInterval | |
Start-Sleep -Milliseconds ($PollingIntervalMin * 60 * 1000) | |
#Create tab separated list of files found in our directory. Also a cache for future reference. | |
$fileString=[string]::Empty | |
ls $FileDirectory -Filter $FilePattern | %{$fileString = $fileString + ($_.Name+"`t")}; | |
foreach ($fileName in $fileString.Split("`t")) | |
{ | |
#Check for new and non-empty FileName | |
if ($existingFileString.Contains($fileName) -eq $false -and $fileName -ne [string]::Empty) | |
{ | |
#File is New | |
Write-Host ('Match Found:' + $fileName) -ForegroundColor Gray | |
#Add File to ExistingFileString | |
$existingFileString = ($existingFileString + $fileName + "`t"); | |
#Invoke any ScriptBlocks on the File | |
if($FileFoundAction -ne $null) | |
{ | |
[string]$path=[string]::Concat($FileDirectory,$fileName) | |
[object[]]$arguments = [string]$path | |
$session = New-PSSession | |
Invoke-Command -ScriptBlock $FileFoundAction -Session $session -ArgumentList ($path) -AsJob | |
} | |
} | |
} | |
} | |
} | |
#Start Polling for New Files | |
PollFileDirectory |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't use this in production rather go for a solution using FileSystemWatcher and Register-ObjectEvent.