问题
I am trying to register an event for when a file is created or changed in a directory. When I try to register the event, the state remains "Not Started" and the event does not work.
function checkFilestatus {
Param($k)
try {
[IO.File]::OpenRead($k).Close()
Copy-Item -Path "$k\" -Destination "\\ServerName\D$\Temp\MyFolder" -Recurse -Force
} catch {
Start-Sleep -Seconds 120
Copy-Item -Path "$k\" -Destination "\\ServerName\D$\Temp\MyFolder" -Recurse -Force
}
}
$filewatcher = New-Object System.IO.FileSystemWatcher
$filewatcher.Path = "D:\MyFolder\Folder2"
$filewatcher.IncludeSubdirectories = $true
$filewatcher.EnableRaisingEvents = $true
Register-ObjectEvent $filewatcher "Created" -SourceIdentifier FileCreated -Action { checkFilestatus($($EventArgs.FullPath)) }
Register-ObjectEvent $filewatcher "Changed" -SourceIdentifier FileChanged -Action { checkFilestatus($($EventArgs.FullPath)) }
Following is the output when I run the script:
Id Name PSJobTypeName State HasMoreData -- ---- ------------- ----- ----------- 40 FileCreated NotStarted False 41 FileChanged NotStarted False
来源:https://stackoverflow.com/questions/46681178/filesystemwatcher-state-not-started