我遇到了IO.FileSystemWatcher的问题。我有一个脚本,当文件复制到某个目录时,它会处理该文件并将其复制到网络上的另一个文件夹。但是有一个问题,它会在fsw触发oncreate事件时开始复制,这会产生错误(文件打开),我希望它只在文件完成复制后启动。重命名和删除工作正常。 cloud.ps1是处理文件并复制它的脚本。 这是监视器脚本的代码:
$watch = '\\HR-ZAG-SR-0011\ACO\ACO2\99. BOX'
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $watch
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$changed = Register-ObjectEvent $watcher "Changed" -Action {
# Write-Host "Changed: $($eventArgs.ChangeType)"
# $watch\cloud.ps1 modify "$($eventArgs.FullPath)"
}
$created = Register-ObjectEvent $watcher "Created" -Action {
Write-Host "Created: $($eventArgs.FullPath)"
.\cloud.ps1 create "$($eventArgs.FullPath)"
}
$deleted = Register-ObjectEvent $watcher "Deleted" -Action {
Write-Host "Deleted: $($eventArgs.FullPath)"
.\cloud.ps1 delete "$($eventArgs.FullPath)"
}
$renamed = Register-ObjectEvent $watcher "Renamed" -Action {
Write-Host "Renamed: $($eventArgs.OldFullPath) to $($eventArgs.FullPath)"
.\cloud.ps1 rename "$($eventArgs.OldFullPath)" "$($eventArgs.FullPath)"
}
答案 0 :(得分:1)
您可以放入一个循环来开始检查是否可以对文件进行写锁定:
While ($True)
{
Try {
[IO.File]::OpenWrite($file).Close()
Break
}
Catch { Start-Sleep -Seconds 1 }
}
只要正在写入文件,您将无法获得写锁定,并且Try将失败。一旦写入完成并且文件关闭,OpenWrite将成功,循环将中断,您可以继续复制文件。