Windows PowerShell从GitHub API下载Zip文件

Windows PowerShell从GitHub API下载Zip文件,windows,git,powershell,api,github,Windows,Git,Powershell,Api,Github,我想按照以下说明编写PowerShell脚本,以ZIP格式下载GitHub repo: 代码确实下载了zip文件,但我在尝试打开zip文件时收到以下错误消息: D:\MyRepo.zip The archive is either in unknown format or damaged 我是PowerShell的新手,非常感谢您的帮助 您可能需要更仔细地查看说明。它说,响应将有一个302重定向到下载的URLInvoke WebRequest不会自动重定向,但会提供响应头 如果您将最后一行更

我想按照以下说明编写PowerShell脚本,以ZIP格式下载GitHub repo:

代码确实下载了zip文件,但我在尝试打开zip文件时收到以下错误消息:

D:\MyRepo.zip
The archive is either in unknown format or damaged

我是PowerShell的新手,非常感谢您的帮助

您可能需要更仔细地查看说明。它说,响应将有一个302重定向到下载的URL
Invoke WebRequest
不会自动重定向,但会提供响应头

如果您将最后一行更改为:

$response = Invoke-WebRequest -Headers $Headers -Uri $Uri -Method Get 
您可以查看$response对象的标题,并使用相同的标题和302 Uri发出另一个
Invoke WebRequest

$RedirectedResponse = Invoke-WebRequest -Headers $Headers -Uri $RedirectedURI -Method Get 
$RedirectedResponse.Content
将包含编码的文件内容,您可以解码并写入本地文件系统

编辑:我访问了一个系统,在那里我可以访问GitHub并测试脚本。我发现第一个响应有一个包含zip文件内容的字节数组。此功能非常有用,不能不共享!以下是下载回购协议的脚本:

$user = 'bjorkstromm'
$repo = 'depends'
$uri = "https://api.github.com/repos/$user/$repo/zipball/"
if(!$cred){$cred = Get-Credential -Message 'Provide GitHub credentials' -UserName $user}
$headers = @{
  "Authorization" = "Basic " + [convert]::ToBase64String([char[]] ($cred.GetNetworkCredential().UserName + ':' + $cred.GetNetworkCredential().Password)) 
  "Accept" = "application/vnd.github.v3+json"
}
$response = Invoke-WebRequest -Method Get -Headers $headers -Uri $uri
$filename = $response.headers['content-disposition'].Split('=')[1]

Set-Content -Path (join-path "$HOME\Desktop" $filename) -Encoding byte -Value $response.Content 

Out File
将创建一个文本文件,而不是二进制文件。非常感谢,很抱歉我错过了说明的内容:(
$user = 'bjorkstromm'
$repo = 'depends'
$uri = "https://api.github.com/repos/$user/$repo/zipball/"
if(!$cred){$cred = Get-Credential -Message 'Provide GitHub credentials' -UserName $user}
$headers = @{
  "Authorization" = "Basic " + [convert]::ToBase64String([char[]] ($cred.GetNetworkCredential().UserName + ':' + $cred.GetNetworkCredential().Password)) 
  "Accept" = "application/vnd.github.v3+json"
}
$response = Invoke-WebRequest -Method Get -Headers $headers -Uri $uri
$filename = $response.headers['content-disposition'].Split('=')[1]

Set-Content -Path (join-path "$HOME\Desktop" $filename) -Encoding byte -Value $response.Content