使用Powershell从Internet下载文件

时间:2014-05-02 23:29:52

标签: http powershell response progress tinyurl

我一直在研究一个使用.txt文件从tinyurls下载多个文件的powershell脚本。我已经成功地使用Jobs来实现这一目标,感谢这个论坛上的人们。 该项目需要下载一些非常大的文件,并且使用当前方法没有进度指示器。我想有些用户可能认为该程序已经死亡。寻找一种方式可以获得下载状态。这是我想出来的,但我迷失了如何将这些信息传递回控制台。有什么建议?

#Checks to see if NT-Download folder is on the Desktop, if not found, creates it
$DOCDIR = [Environment]::GetFolderPath("Desktop")
$TARGETDIR = "$DOCDIR\NT-Download"
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

$filepaths = Resolve-Path "files.txt"

Get-Content "$filepaths" | Foreach {
Start-Job {
    function Save-TinyUrlFile
    {
        PARAM (
            $TinyUrl,
            $DestinationFolder
        )

        $response = Invoke-WebRequest -Uri $TinyUrl
        $filename = [System.IO.Path]::GetFileName($response.BaseResponse.ResponseUri.OriginalString)
        $filepath = [System.IO.Path]::Combine($DestinationFolder, $filename)
        $totalLength = [System.Math]::Floor($response.get_ContentLength()/1024) 
        $responseStream = $response.GetResponseStream()
        $buffer = new-object byte[] 10KB
        $count = $responseStream.Read($buffer,0,$buffer.length) 
        $downloadedBytes = $count
        try
        {
            $filestream = [System.IO.File]::Create($filepath)
            $response.RawContentStream.WriteTo($filestream)
            $filestream.Close()
            while ($count -gt 0) 
            { 
                [System.Console]::CursorLeft = 0 
                [System.Console]::Write("Downloaded {0}K of {1}K", [System.Math]::Floor($downloadedBytes/1024), $totalLength) 
                $targetStream.Write($buffer, 0, $count) 
                $count = $responseStream.Read($buffer,0,$buffer.length) 
                $downloadedBytes = $downloadedBytes + $count 
            } 
                         "`nFinished Download" 
            $targetStream.Flush()
            $targetStream.Close() 
            $targetStream.Dispose() 
            $responseStream.Dispose() 
        }
        finally
        {
            if ($filestream)
            {
                $filestream.Dispose();
            }
        }
    }

    Save-TinyUrlFile -TinyUrl $args[0] -DestinationFolder $args[1]
} -ArgumentList $_, "$TARGETDIR"

}

1 个答案:

答案 0 :(得分:0)

查看Write-Progress

  

PS C:> for($ i = 1; $ i -le 100; $ i ++)   {write-progress -activity"正在搜索" -status" $ i%完成:" -percentcomplete $ i;}