PowerShell 下载文件

2022-04-15 2126点热度 0条评论

最近在堡垒机上面做开发,遇到一个非常恶心的事情。机器使用的是Windows Server 2008,里面就一个IE,想下载一个软件都是各种权限受限!

那么就想绕过这个浏览器下载的方式,通常情况下可以拷贝个WgetcUrl去下载,但这也需要去找到这个小程序。

其实在Windows上默认是带了PowerShell的,它本来就是个命令行,那么它肯定也有可以下载文件的方式。搜索引擎一搜,果然还有不少!

下载文件实例

自带命令下载文件的几种方式

  1. Invoke-WebRequest
  2. Invoke-RestMethod
  3. Start-BitsTransfer
  4. System.Net.WebClient

Invoke-WebRequest

Description

The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service. It parses the response and returns collections of forms, links, images, and other significant HTML elements.
This cmdlet was introduced in Windows PowerShell 3.0.
# 下载文件
Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.10.4/python-3.10.4-amd64.exe" -OutFile "python-3.10.4-amd64.exe"

# 挂代理
Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.10.4/python-3.10.4-amd64.exe" -OutFile "python-3.10.4-amd64.exe" -Proxy "http://127.0.0.1:7890"

# 更多的的参数
Get-Help Invoke-WebRequest
Invoke-WebRequest
说明

此种方式是先将流读取至内存中,待全部读取完成再写入文件。因此,该方式是不适合做大文件下载的。

Invoke-RestMethod

Invoke-RestMethodInvoke-WebRequest类似,区别在于RestMethod支持Json和XML类型,会尝试适当的解码器来读取。

# 下载文件
Invoke-RestMethod -Uri "https://www.python.org/ftp/python/3.10.4/python-3.10.4-amd64.exe" -OutFile "python-3.10.4-amd64.exe" -Proxy "http://127.0.0.1:7890"

# 更多参数
Get-Help Invoke-RestMethod
Invoke-RestMethod

Start-BitsTransfe

Start-BitTransfer是windows自带的一个程序,支持断点续传、多文件,因此它是一个非常适用于下载的命令。

# 下载文件
Start-BitsTransfer -Source "https://www.python.org/ftp/python/3.10.4/python-3.10.4-amd64.exe" -Description "python-3.10.4-amd64.exe"

# 下载多个文件
Import-CSV filelist.txt | Start-BitsTransfer
filelist.txt

Source, Destination
https://www.python.org/ftp/python/3.10.4/python-3.10.4-amd64.exe, python-3.10.4-amd64.exe
https://webcdn.m.qq.com/spcmgr/download/QQ9.5.9.28650.exe, QQ9.5.9.28650.exe

Start-BitsTransfe

System.Net.WebClient

(New-Object System.Net.WebClient).DownloadFile("https://webcdn.m.qq.com/spcmgr/download/QQ9.5.9.28650.exe","qq.exe")

Jalena

原创内容,转载请注明出处! 部分内容来自网络,请遵守法律适用!

文章评论