我正在使用以下代码启动
$folder = '....'
$filter = '*.csv'
$fsw = New-Object IO.FileSystemWatcher $folder, $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
... #execute a program to read the files,
... #may fail because file is still being writing..... }
但是,我会在创建文件后立即触发操作。可能有数百个拥抱文件要在文件夹中转储/复制。是否可以测试文件是否完成?
答案 0 :(得分:1)
一种可能性:
Try {
[IO.File]::OpenWrite($File).Close()
#Do something with file
}
Catch {}
如果文件已写入并已关闭[IO.File]::OpenWrite($File).Close()
将打开文件进行写入,然后立即关闭它。如果它仍然被写入,则无法获得写锁定,该命令将失败,脚本将进入Catch块并等待下一个LastWrite事件。