PowerShell从公共Github下载exe



我无法从Github下载.exe文件。脚本适用于不同的网站,下载文件时不会出现问题。

https://github.com/ShareX/ShareX/releases/tag/v13.1.0

这是我正在尝试下载的.exe文件:https://github.com/ShareX/ShareX/releases/download/v13.1.0/ShareX-13.1.0-setup.exe

>$DownloadUrl = "https://github.com/ShareX/ShareX/releases/download/v13.1.0/ShareX-13.1.0-setup.exe"
>$WebResponse = Invoke-WebRequest -Uri "$DownloadUrl" -Method Head
Invoke-WebRequest : The remote server returned an error: (403) Forbidden.
At line:2 char:16
+ $WebResponse = Invoke-WebRequest -Uri "$DownloadUrl" -Method Head
+                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

完整脚本:

[Net.ServicePointManager]::SecurityProtocol = "Tls, Tls11, Tls12, Ssl3"
$DownloadUrl = "https://github.com/ShareX/ShareX/releases/download/v13.1.0/ShareX-13.1.0-setup.exe"
$WebResponse = Invoke-WebRequest -Uri "$DownloadUrl" -Method Head
Write-Output "Downloading $DownloadUrl"
Start-BitsTransfer -Source $WebResponse.BaseResponse.ResponseUri.AbsoluteUri.Replace("%20", " ") -Destination "C:UsersPegavoDesktopPS"

您只需将Invoke-WebRequest-OutFile参数一起使用即可。

Invoke-WebRequest https://github.com/ShareX/ShareX/releases/download/v13.1.0/ShareX-13.1.0-setup.exe -OutFile "ShareX-13.1.0-setup.exe"

此命令将从GitHub下载文件,并将结果存储到当前目录中的文件中。

或者,您可以使用WebClient

$webClient = New-Object System.Net.WebClient
$webClient.DownloadFile("https://github.com/ShareX/ShareX/releases/download/v13.1.0/ShareX-13.1.0-setup.exe", "E:yourpathShareX-13.1.0-setup.exe")

我在本地机器上测试了这两个。两者都奏效了。

此外,如果你想了解为什么StartBitsTransfer不起作用,请点击此处。


编辑:

您可以像这样使用Split-Path:自动获取文件名

$url = "https://github.com/ShareX/ShareX/releases/download/v13.1.0/ShareX-13.1.0-setup.exe"
$file= Split-Path $url -Leaf #file is ShareX-13.1.0-setup.exe now
Invoke-WebRequest $url -OutFile $file

使用HEAD有原因吗?GET似乎起作用

最新更新