Your code works... on linux anyway. Here's what I setup:
test.ps1:
$sourcepath = '/home/veefu/watched/sourcefolder'
$destpath = '/home/veefu/watched/destfolder'
$watcher = New-object System.io.filesystemwatcher
$watcher.path = $sourcepath
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
$action = {
$path = $event.SourceEventARgs.FullPath
Move-Item -Path $path -Destination $destpath
}
Register-ObjectEvent $watcher 'Created' -action $action
Started with:
. ./test.ps1
To test, I downloaded and saved a .jpg file with chrome to the $sourcepath
. The following errors were emitted to the listening job, but the .jpg file was moved in the end:
> get-job |Receive-Job
Move-Item : Cannot find path '/home/veefu/watched/sourcefolder/after
night out.JPG.crdownload' because it does not exist. At
/home/veefu/watched/test.ps1:14 char:5
+ Move-Item -Path $path -Destination $destpath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (/home/veefu/wa....JPG.crdownload:String) [Move-Item],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand Move-Item
: Cannot find path '/home/veefu/watched/sourcefolder/after night
out.JPG.crdownload' because it does not exist. At
/home/veefu/watched/test.ps1:14 char:5
+ Move-Item -Path $path -Destination $destpath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (/home/veefu/wa....JPG.crdownload:String) [Move-Item],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand
It's possible that the events on Linux differ from those generated on Windows.
It's also possible that the file size I chose for testing leads to different results than the one you chose. Judging by the errors, the .jpg seemed to already be renamed by the time the listener tried to handle the event.
You may try reading the error events from the watching job to get a clue as to the problem with:
Get-Job | Receive-Job
Also, you don't need the while($true) {sleep 5}
if you're running your script from a powershell console; The job responsible for listening should persist as long as your powershell process does.
For that matter, you may need to check how many jobs you have running and clean up any left-overs using Get-Job
, Stop-Job
and Remove-Job