通过PSSession下载PS< 5文件

时间:2018-04-10 13:19:45

标签: powershell

如何通过PSSession从远程服务器下载文件?我知道PS5引入了Copy-Item -FromSession,但本地和远程可能都没有运行PS5。我的文件也很大,因此简单的Get-Content可能会有问题。

1 个答案:

答案 0 :(得分:2)

您可以将远程端的文件作为字节数组的序列读取,通过远程处理将它们流式传输,然后将它们组装回本地文件:

function DownloadSingleFile {
    param(
        [System.Management.Automation.Runspaces.PSSession] $FromSession,
        [string] $RemoteFile,
        [string] $LocalFile,
        [int] $ChunkSize = 1mb
    )
    Invoke-Command -Session $FromSession -ScriptBlock {
        param(
            [string] $FileName,
            [int] $ChunkSize
        )
        $FileInfo = Get-Item -LiteralPath $FileName
        $FileStream = $FileInfo.OpenRead()
        try {
            $FileReader = New-Object System.IO.BinaryReader $FileStream
            try {
                for() {
                    $Chunk = $FileReader.ReadBytes($ChunkSize)
                    if($Chunk.Length) {
                        ,$Chunk
                    } else {
                        break;
                    }
                }
            } finally {
                $FileReader.Close();
            }
        } finally {
            $FileStream.Close();
        }
    } -ArgumentList $RemoteFile, $ChunkSize | ForEach-Object {
        $FileName = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($LocalFile)
        $FileStream = [System.IO.File]::Create($FileName)
    } {
        $FileStream.Write($_, 0, $_.Length)
    } {
        $FileStream.Close()
    }
}