I am looking for help in my Powershell script.
If Directory log location C:\Users\10146187\Downloads\Syslogd does not have any new file created or changed for last 30 minutes, I want to run function "RunMyStuff". Also i do not have Unregister-function. Not sure, where do i put it. Thanks.
Function RunMyStuff {
# this is the bit I want to happen when there is no file created for 30 mins under C:\Users\10146187\Downloads\Syslogd
Start-Process 'C:\windows\system32\calc.exe'
Write-Host $global:FileCreated
}
Function Watch {
$global:FileCreated = $false
$folder = "C:\Users\10146187\Downloads\Syslogd"
$filter = "*.*"
$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
Register-ObjectEvent $Watcher "Created" -Action {$global:FileCreated = $true} > $null
Start-Sleep -Seconds 120
while($true){
while ($global:FileCreated -eq $true){
Start-Sleep -Seconds 600
Write-Host $global:FileCreated
}
RunMyStuff
$global:FileCreated = $false
}
}
Watch
This might be an example of what you're looking for. It uses a Timer event with a FileWatcher event.
function RunMyStuff()
{
Write-Host "$(get-date) RunMyStuff (no files added within last 10 seconds)"
# Start-Process "calc.exe"
}
function Watch ($folder) {
Write-Host "Watching $((Get-Item $folder).Fullname)"
$global:FileCreated = $true
$filter = "*.*"
$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
Register-ObjectEvent -InputObject $watcher -EventName "Created" -SourceIdentifier "myFileWatcher" -Action {
$global:timer.Stop()
$global:FileCreated = $true
$global:timer.Start()
} > $null
$global:timer = New-Object Timers.Timer
$global:timer.Interval = 10000
Register-ObjectEvent -InputObject $global:timer -EventName "Elapsed" -SourceIdentifier "myTimer" -Action {
$global:FileCreated = $false
} > $null
$global:timer.Start()
try {
while ($true) {
Start-Sleep -Seconds 1
if (!$global:FileCreated) {
RunMyStuff
$global:FileCreated = $true
}
}
}
finally {
Unregister-Event -SourceIdentifier "myFileWatcher"
Unregister-Event -SourceIdentifier "myTimer"
}
}
Watch "C:\"