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. JDBC及DBUtils

    1.JDBC2.DBUtils ###01JDBC概念和数据库驱动程序 * A: JDBC概念和数据库驱动程序 * a: JDBC概述 * JDBC(Java Data Base Connectivi ...

  2. Python常用模块之Pygame(手册篇:首页)

    Pygame手册官方网址:http://www.pygame.org/docs/ Pygame首页 说明文档: 自述 关于Pygame的基本信息,它是什么,谁参与了以及在哪里找到它. 安装 在几个平台 ...

  3. 关于0x80000000为什么等于-2147483648和负数在内存上储存的问题

    转载自大佬的博客https://blog.csdn.net/youyou362/article/details/72667951/ 1·先说明负数怎么储存 (1)十进制负数是以其补码储存在内存上. 验 ...

  4. LeetCode 289. Game of Life (C++)

    题目: According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a ce ...

  5. P4语法(5) Package

    Package 对于package这个概念,类似于将一个框架中各组成部件以一个规律进行打包,以正常运转. 基于一个架构去编写一个新的pipeline的时候,需要先了解初始化的时候需要提供那些东西,pa ...

  6. 寒假作业2:简化电梯设计elevator

    Github仓库地址:hua-kui 寒假学习计划:学习计划 - 题目背景 一栋10层的大楼(楼层编号1-10),设有一台无限载重的电梯,初始时电梯停在1层.电梯移动1层的耗时为1,在某一层停靠的耗时 ...

  7. mysql hql异常

    org.springframework.dao.InvalidDataAccessResourceUsageException:  could not execute query; nested ex ...

  8. java锁有哪些类(转)

    转载来源:http://www.cnblogs.com/lxmyhappy/p/7380073.html 1.Java都有哪些锁? 公平锁/非公平锁 可重入锁 独享锁/共享锁 互斥锁/读写锁 乐观锁/ ...

  9. Java对象创建过程补遗

    一.static修饰的东东是属于这个类的,是所有的该类的实例共享的,因此它们的初始化先于实例对象的初始化. 二.Java中没有静态构造方法,但是有静态代码块.当类中同时存在静态代码块和静态成员变量声明 ...

  10. 初识 es6之 const

    const声明一个只读的常量.一旦声明,常量的值就不能改变. 例子: const a=12; a=2;//报错,const 声明的是常量,不能改 const声明的变量不得改变值,这意味着,const一 ...