'Powershell: Why would Move-Item on a file result in the target file being 0 bytes?
I notice that this code:
Move-Item $path -Destination $destination -Force -Verbose
Often results in the destination file being 0 bytes (where the source file is say 90K). I can see the file size is 0 a couple of ways:
- In interactive File Explorer, it shows as 0 bytes
- When I run a file converter on the file, it throws an error (because the file is 0 bytes)
Historically, my code did not check for file size. I just started noticing the problem intermittently. Now I have checks, but that isn't perfect. Would prefer for it to be reliable!
The code works %99 of the time. Permissions are not the issue. (It is 100% local operations, on simple directories. Single file operations. Zero remote anything. This is c:\foo\bar.txt to c:\foo2\bar.txt)
How to chase/resolve?
Solution 1:[1]
The issue is that the file was being downloaded by a web browser, and in some cases there is a delay for the file to be written out.
At least with firefox, there is an interesting behavior, downloading foo.wav:
gooked-123132asdfas.wav.part // appears first on file system foo.wav // appears, with file size either correct or 0 foo.wav // shows up with contents (if it started as zero
There can be 150+ msec between each of those steps. Even 350+.
The solution was:
$i = 1
while (((Get-Item $path).length -eq 0kb) -and ([System.IO.File]::Exists($path)))
{
# This loop is actually constructive, because it forces the process to wait until the
# the file has been written out....
Write-Host "file size of $path is " (Get-Item $path).length
Start-Sleep -Seconds .1
$i++
# If the file stays at 0 bytes, get out of the loop and forget this file...
# means there is a download issue. Exit the whole larger block.
if ($i=11) {continue processingLoop}
}
This is done prior to the Move-Item call, and the whole thing gets a lot more reliable. (Well, perfectly reliable so far.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonesome Reinstate Monica |
