Powershell - Check if file is finished writing

喜欢而已 提交于 2019-12-23 20:26:05

问题


I have a powershell code that acts as a file listener on a given folder path. The listener kicks off a command line call to another program that opens and plays with the file.

The problem is that the powershell code Immediately kicks off the command line call if any file is put into this folder. This is a problem if the file is very large (say 100+mb) because when a person copies the file into the folder, the file may only be 5% done 'writing' when the command function kicks off and tries to open the file (and fails).

is there a way in powershell to check if a file is still being written too? That way I could build a loop that would check every x seconds and only run once the write was completed?

Does a file maintain a "lock" if it is being written too? Can this be checked for in Powershell?

Thanks everyone!


回答1:


There may be a lock check available in System.IO.FileInfo, or somewhere like that but I use a simple length check. It goes in the called script not the file watcher script.

$LastLength = 1
$NewLength = (Get-Item $FileName).length
while ($NewLength -ne $LastLength) {
   $LastLength = $NewLength
   Start-Sleep -Seconds 60
   $NewLength = (Get-Item $FileName).length
}


来源:https://stackoverflow.com/questions/29394358/powershell-check-if-file-is-finished-writing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!