Reputation: 91
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!
Upvotes: 4
Views: 6345
Reputation: 22392
To answer your main question which is how to check status of file download, the easiest is to check the last modified time of file to see if it has exceeded 5 minutes (just to be on the safe side for network latency etc). I had multiple files so the below code is at the folder level but you could simply change the path for single file too.
#print a user feed back to see if downloading is completed
write-host "started downloading"
function status_checker() {
if (((get-date) - $lastWrite) -gt $timespan) {
write-host "Downloading completed"
break
} else {
write-host "still downloading" (Get-Date)
}
}
#check every 10 seconds
while(1)
{
status_checker
# 5 minutes
start-sleep -seconds 300
}
Upvotes: 0
Reputation: 1623
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
}
Upvotes: 5