views:

619

answers:

2

Is there any way to copy a really large file (from one server to another) in Powershell AND display it's progress?

There are solutions out there to use Write-Progress in conjunction with looping to copy many files and display progress. However I can't seem to find anything that would show progress of a single file.

Any thoughts?

+1  A: 

Not that I'm aware of. I wouldn't recommend using copy-item for this anyway. I don't think it has been designed to be robust like robocopy.exe to support retry which you would want for extremely large file copies over the network.

Keith Hill
Valid point. In this particular case I'm not too worried about robustness. It's copying a 15gig file between two servers on the same back-plane. However in other situations I would definitely consider a more robust solution.
Jason Jarrett
+3  A: 

I haven't heard about progress with Copy-Item. If you don't want to use any external tool, you can experiment with streams. The size of buffer varies, you may try different values (from 2kb to 64kb).

function Copy-File {
    param( [string]$from, [string]$to)
    $ffile = [io.file]::OpenRead($from)
    $tofile = [io.file]::OpenWrite($to)
    Write-Progress -Activity "Copying file" -status "$from -> $to" -PercentComplete 0
    try {
        [byte[]]$buff = new-object byte[] 4096
        [int]$total = [int]$count = 0
        do {
            $count = $ffile.Read($buff, 0, $buff.Length)
            $tofile.Write($buff, 0, $count)
            $total += $count
            if ($total % 1mb -eq 0) {
                Write-Progress -Activity "Copying file" -status "$from -> $to" `
                   -PercentComplete ([int]($total/$ffile.Length* 100))
            }
        } while ($count -gt 0)
    }
    finally {
        $ffile.Close()
        $tofile.Close()
    }
}
stej
Interesting solution.When I tried it I received an error - Cannot convert value "2147483648" to type "System.Int32". Error: "Value was either too large or too small for an Int32."After replacing the [int] to a [long], it worked great.Thanks
Jason Jarrett
That means that you copy files bigger than 2GB? I guess so. I'm glad it works :)
stej