Adam
Adam

Reputation: 59

FileSystemWatcher not firing events till PowerShell closes

I have a script (below) that watches a folder that the .ps1 script sits in. When a file is created it fires a .bat file to do a job.

Initially it would run and close immediately. So I added '''Start-Sleep -s 50'''

It works but it only triggers the .bat launch when the PowerShell window closes.

(As I don't know how long it will be till a file turns up in the folder, this is kind of useless).

Ideally I could do with the .bat file launching as soon as the new file is created, which in turn then closes the PowerShell window

$configFilePath = $PSScriptRoot
$filter = '*.*'

$fsw = New-Object IO.FileSystemWatcher $configFilePath, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
    Out-File -FilePath c:\temp\log\Filelog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
    Set-Location "$PSScriptRoot"
    Start-Process "$PSScriptRoot\PS_Run.bat"
}

Start-Sleep -s 50

Upvotes: 1

Views: 1651

Answers (1)

Axel Andersen
Axel Andersen

Reputation: 1128

You can replace Start-Sleep with:

Wait-Event -SourceIdentifier FileCreated

Then you need to add an exit command to your watcher like this:

Start-Process "$PSScriptRoot\PS_Run.bat"
exit
}

Since you cannot exit the console from the filewatcher, you can do this instead:

$configFilePath = $PSScriptRoot
$filter = '*.*'

$fsw = New-Object IO.FileSystemWatcher $configFilePath, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
    Out-File -FilePath c:\temp\log\Filelog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
    Set-Location "$PSScriptRoot"
    Start-Process "$PSScriptRoot\PS_Run.bat"
}
Wait-Event -SourceIdentifier FileCreated -Timeout 50 # or no of seconds before file shows up.

When run as a scheduled task, this will execute the bat file as soon as a new file is created and close the console when the timeout is reached.

Upvotes: 1

Related Questions