Perhaps the greatest strength of PowerShell is it's foundation on the .NET framework. The .NET framework enables almost unlimited possibilites inside the scripting realm. This blessing can equally be a curse as things can get complicated. Fast.

This post will describe three methods for downloading files using PowerShell - weighed up with their pros and cons.

Test setup

Today's testing is not highly scientific. The point is to show the difference in execution time and performance.

The test setup consists of PowerShell 4 running on Windows 8.1 x64 with my VDSL connection curently synced at 35.9/10.4 mbps.

I will be downloading a test file from Internode at the following URL: http://­mirror.­internode­.on.­net/­pub/­test/­10­m­e­g­.­t­e­s­t. The scripts will be executed 10 times each with the average displayed as the result.

Let's get started!

1. Invoke-WebRequest

The first and most obvious option is the Invoke-WebRequest cmdlet. It is built into PowerShell and can be used in the following method:

$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

Time taken: 27 seconds

Pros

With the cmdlet already available it is super easy to get started and use. Integration with Write-Progress is handy while watching paint dry scripts run (assuming you know the total file size). Cookies can also be persisted between mutiple requests through the use of the -Session and -WebSession parameters. 

Cons

Speed. This cmdlet is slow. From what I have observed, the HTTP response stream is buffered into memory. Once the file has been fully loaded, it is flushed to disk. This adds a huge performance hit and potential memory issues for large files. If anyone knows specifics on how this cmdlet operates, let me know!.

Another potentially serious con for this method is the reliance on Internet Explorer. For example, this cmdlet cannot be used on Windows Server Core edition servers as the Internet Explorer binaries are not included by default. In some cases you can use the -UseBasicParsing parameter, but it does not work in all cases.

Verdict

This cmdlet shines when you need to persist cookies across multiple requests (for instance HTTP Forms Auth before downloading the file).

Performance is good enough for small downloads, but there are definitely better options for situations where speed is required. If the script is to be run on a server running Windows Server Core, choose a more universal method.

2. System.Net.WebClient

A common .NET class used for downloading files is the System.Net.WebClient class.

$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date $wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)
#OR
(New-Object System.Net.WebClient).DownloadFile($url, $output) Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

Time taken: 7 seconds

Pros

This method is also easy to use. Not as syntactically nice as Invoke-RestMethod - yet can still be executed on a single line. Speed is great as the HTTP response stream is buffered to disk throughout the download process.

There is also the option of System.Net.WebClient.DownloadFileAsync(). This can be very handy if you'd like your script to continue while the file downloads in parallel.

Cons

There is no visible progress indicator (or any way to query the progress mid transfer). It essentially blocks the thread until the download completes or fails. This isn't a major con, however sometimes it is handy to know how far through the transfer you are.

Verdict

System.Net.WebClient is my preferred option when file downloads are required. Anything that increases the performance of my scripts is a winner in my books. This method is also fully compatible on Server Core machines and 100% compatible with your Azure Automation runbooks.

3. Start-BitsTransfer

If you haven't heard of BITS before, check this out. BITS is primarily designed for asynchronous file downloads, but works perfectly fine synchronously too (assuming you have BITS enabled).

$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $output
#OR
Start-BitsTransfer -Source $url -Destination $output -Asynchronous Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

Time taken: 6 seconds

Pros

This method proved to be the fastest in my test cases! Extensive integration with Write-Progress gives you a clear indicator of the file size and progress. The -Asynchronous flag can be used to queue transfers asychronously. This method is also incredibly flexible supporting separate credentials for the destination server AND web proxy, if required.

Personally, the biggest benefit to using the Start-BitsTransfer method is the ability to set retry actions on failure and limiting the amount of bandwidth available to a transfer.

Cons

While BITS is enabled by default on many machines, you can't guarantee it is enabled on all (unless you are actively managing this). Also with the way BITS is designed, if other BITS jobs are running in the background, your job could be queued or run at a later time hindering the execution of your script.

Verdict

This method is perfect for scenarios where you want to limit the bandwidth used in a file download or where time isn't a major issue. I have used this to sync files nightly at full speed and during the day at half speed using Transfer Policies. BITS is also easy to monitor and audit.

Conclusion

We can see the obvious/easiest choice isn't always the best. I would recommend System.Net.WebClient due to it's universal nature and performance. BITS my second choice due to it's flexibility and managability.

Do you know other methods? Let me know!

https://blog.jourdant.me/post/3-ways-to-download-files-with-powershell

3 ways to download files with PowerShell的更多相关文章

  1. Asp.net core 学习笔记 ( upload/download files 文件上传与下载 )

    更新 :  2018-01-22  之前漏掉了一个 image 优化, 就是 progressive jpg refer : http://techslides.com/demos/progressi ...

  2. 安装Laravel遇到You must enable the openssl extension to download files via https问题

    刚看了一篇文章说了2014年最火的10个php框架,看到了Laravel,于是便自己试试,孰料刚安装便遇到了一个问题(由于一不小心关掉了cmd,此处无法截图显示),便是如文章标题中所说的那样,goog ...

  3. [AWS - EC2] 如何向 Amazon Linux 2 实例传输文件,下载文件。How to send/ download files from Amazon Linux 2 Instance

    1. 需要: 安装 WinSCP 2. 需要: PuTTY 生成的ppk格式密钥, 没有的话请移步此文章,完成1, 2, 3步即可. 3. 打开 WinSCP , 如果提示已经有PuTTY配置是否导入 ...

  4. How To Use XDOLoader to Manage, Download and Upload Files? (文档 ID 469585.1)

    Applies to: BI Publisher (formerly XML Publisher) - Version 5.6.3 to 5.6.3 [Release 5] Information  ...

  5. How To Use XDOLoader to Manage, Download and Upload Files? (DOC ID 469585.1)

    In this Document Goal Fix     Downloading Files   Uploading Files References Applies to: BI Publishe ...

  6. SharePoint 2013 – Workflow Manager 1.0 offline download

    [http://sharepointdeal.wordpress.com/2013/03/13/sharepoint-2013-workflow-manager-1-0-offline-downloa ...

  7. How To Download Youtube Videos Without any software

    https://www.quora.com/What-is-the-best-way-to-download-YouTube-videos-for-free There are various met ...

  8. Download/Attach source-code/java-docs with maven dependencies

    I am using Maven in my projects from last couple of years, and the automatically downloading the Jar ...

  9. 通过PowerShell命令给Azure VM添加CustomScriptExtension

    Azure的VM提供了一种管理工具叫Azure VM Extension.它实现了一些管理虚拟机所需要的重要功能,比如:重设密码.设置RDP参数.以及许多其他关键的功能,并且Azure VM一直在添加 ...

随机推荐

  1. python_MySQL 数据库操作

    Python中的mysql操作可以使用MySQLdb模块来完成.它符合Python社区设计的Python Database API SpecificationV2.0标准,所以与其他的数据库操作的AP ...

  2. BVT与冒烟测试

    [BVT的释义] BVT的全称是Build Verification Test.可以说这个全称就是BVT的定义了. BVT只验证build构建的成功与失败,不深入测试构建好的build的功能.性能等等 ...

  3. php json 转换

    在PHP语言中使用JSON   作者: 阮一峰 日期: 2011年1月14日 目前,JSON已经成为最流行的数据交换格式之一,各大网站的API几乎都支持它. 我写过一篇<数据类型和JSON格式& ...

  4. Thunder团队——选题展示

    团队名称:Thunder 组长:王航 成员:李传康.代秋彤.邹双黛.苗威.宋雨.胡佑蓉.杨梓瑞 项目名称:爱阅app 视频展示: http://www.cnblogs.com/lick468/p/76 ...

  5. POJ 2484(对称博弈)

    题目链接:http://poj.org/problem?id=2484 这道题目大意是这样的,有n个硬币围成一圈,两个人轮流开始取硬币(假设他们编号从1到n),可以选择取一枚或者取相邻的两枚(相邻是指 ...

  6. [转]精选!15个必备的VSCode插件

    Visual Studio Code 是由微软开发的一款免费.跨平台的文本编辑器.由于其卓越的性能和丰富的功能,它很快就受到了大家的喜爱. 就像大多数 IDE 一样,VSCode 也有一个扩展和主题市 ...

  7. 5th 各组作品alpha发布体会

    1.  俄罗斯方块   武志远 可以进行游戏,界面很友好,游戏运行也很流畅,并找到两名同学现场体验,游戏完成度很好. 2.  连连看游戏  张金生 可以进行游戏,实现了背景音乐播放等附加功能,界面清晰 ...

  8. 对mysql联合索引中的字段进行合理排序

    在MySQL的where条件中,有时会用到很多的条件,通常为了加快速度会把这些字段放到联合索引中,可以更快的提高搜索速度: 但是对联合索引中字段顺序的合理排序,便更能提高速度 例子:select * ...

  9. iOS 关于MVC和MVVM设计模式的那些事

    一.概述 在 iOS 开发中,MVC(Model View Controller)是构建iOS App的标准模式,是苹果推荐的一个用来组织代码的权威范式.Apple甚至是这么说的.在MVC下,所有的对 ...

  10. 第78天:jQuery事件总结(一)

    jQuery事件总结(一)    现在就一点一点积累自己的知识体系,记录自己学到的和自己所理解的jQuery. JavaScript和HTML之间的交互式通过用户和浏览器操作页面时引发的事件机制来处理 ...