This is an example how to use inotify with powershell
# find the path to the desktop folder:
$desktop = [Environment]::GetFolderPath('Desktop')
# specify the path to the folder you want to monitor:
$Path = $desktop
# specify which files you want to monitor
$FileFilter = '*'
# specify whether you want to monitor subfolders as well:
$IncludeSubfolders = $true
# specify the file or folder properties you want to monitor:
$AttributeFilter = [IO.NotifyFilters]::FileName, [IO.NotifyFilters]::LastWrite
# specify the type of changes you want to monitor:
$ChangeTypes = [System.IO.WatcherChangeTypes]::Created, [System.IO.WatcherChangeTypes]::Deleted, [System.IO.WatcherChangeTypes]::Changed
# specify the maximum time (in milliseconds) you want to wait for changes:
$Timeout = 1000
# define a function that gets called for changes:
# (or create more functions - perhaps one per change type)
function Invoke-SomeAction
{
param
(
[Parameter(Mandatory)]
[System.IO.WaitForChangedResult]
$ChangeInformation
)
Write-Warning 'Change detected:'
$ChangeInformation | fl * | Out-String | Write-Host -ForegroundColor DarkYellow
write-host ""; write-host ""; write-host ""
}
# use a try...finally construct to release the
# filesystemwatcher once the loop is aborted
# by pressing CTRL+C
try
{
Write-Warning "FileSystemWatcher is monitoring $Path"
# create a filesystemwatcher object
$watcher = New-Object -TypeName IO.FileSystemWatcher -ArgumentList $Path, $FileFilter -Property @{
IncludeSubdirectories = $IncludeSubfolders
NotifyFilter = $AttributeFilter
}
# start monitoring manually in a loop:
do
{
# wait for changes for the specified timeout
# IMPORTANT: while the watcher is active, PowerShell cannot be stopped
# so it is recommended to use a timeout of 1000ms and repeat the
# monitoring in a loop. This way, you have the chance to abort the
# script every second.
$result = $watcher.WaitForChanged($ChangeTypes, $Timeout)
# if there was a timeout, continue monitoring:
if ($result.TimedOut) { continue }
Invoke-SomeAction -Change $result
# the loop runs forever until you hit CTRL+C
} while ($true)
}
finally
{
# release the watcher and free its memory:
$watcher.Dispose()
Write-Warning 'FileSystemWatcher removed.'
}
Create a Windows Service
### Create Service
$params = @{
Name = "Inotify Job Desktop"
BinaryPathName = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe c:\scripts\this_script.ps1'
#DependsOn = "NetLogon"
DisplayName = "Test Service"
StartupType = "Manual"
Description = "This is a test inotify service."
}
New-Service @params