git - 尝试使用 Powershell 从 Azure DevOps Git 存储库下载文件

标签 git powershell azure-devops

所以我在 Azure DevOps 中有一个 Git 存储库,其 URL 如下

https://[$server]/tfs/[$company]/[$project]/_git/[$repoName]

我可以通过附加类似这样的内容来访问该存储库中的各个文件:

?path=/[$folder]/[$fileName]

我正在尝试使用 Powershell 将特定文件从此存储库下载到我计算机上的相应位置和文件名,如下所示:

$sourcePath = "https://[$server]/tfs/[$company]/[$project]/_git/[$repoName]?path=/[$folder]/[$fileName]&download=true"
$filePath = "C:\Documents\[$folder]\[$fileName]"
Invoke-RestMethod -Uri $sourcePath -Method Get -Headers @{Authorization=("Basic {0}" -f [$AuthInfo])} -OutFile $filePath

这样做不是用 repo 中的文件替换本地文件,而是用响应正文的内容替换本地文件的内容。我发现奇怪的是,我一直在做的所有谷歌搜索都说要这样做,即使 Microsoft article on Invoke-RestMethod实际上解释了这就是 -OutFile 所做的。

请注意,我也尝试过 Invoke-WebRequest....同样的事情。

那么如何将实际文件从 repo 下载到我想要的本地目标(或将本地目标文件的内容替换为 repo 文件的内容)?

另外,有没有办法指定从哪个分支获取文件?也许我也应该以某种方式使用 Git powershell 命令?我所做的关于从 git 存储库下载的所有其他谷歌搜索都得出了关于 GitHub 的结果。

谢谢!

最佳答案

通过以下模板使用 rest api:

获取 https://{tfs_url}/{collection_name}/{project}/_apis/git/repositories/{repositoryId}/items?path={path}

查看文档:Items - Get , Example - Download

我使用以下代码在构建管道中复制文件(使用 System.Net.WebClient):

$user = ""
$token = $env:SYSTEM_ACCESSTOKEN
$teamProject = $env:SYSTEM_TEAMPROJECT
$orgUrl = $env:SYSTEM_COLLECTIONURI
$repoName = "REPO_NAME"

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

    function InvokeGetFileRequest ($GitFilePath, $OutFilePath)
    {
        Write-Host "Download file" $GitFilePath "to" $OutFilePath
     
        $uriGetFile = "$orgUrl/$teamProject/_apis/git/repositories/$repoName/items?scopePath=$GitFilePath&download=true&api-version=6.1-preview.1"
    
       Write-Host "Url:" $uriGetFile
    
        $wc = New-Object System.Net.WebClient
        $wc.Headers["Authorization"] = "Basic {0}" -f $base64AuthInfo
        $wc.Headers["Content-Type"] = "application/json";
        $wc.DownloadFile($uriGetFile, $OutFilePath)
    }

关于git - 尝试使用 Powershell 从 Azure DevOps Git 存储库下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67272942/

相关文章:

azure - 如何在同一 Azure 项目中的管道之间传输 Azure Pipelines 中的项目?

git - 在git中跨分支查找标签 merge 提交

git - 修改 merge 分支后如何修改 merge ?

powershell - switch 语句中多个值的 PowerShell 语法是什么?

azure - 无法使用 CLI 创建 AKS 群集

azure-devops - Azure DevOps 将 Nuget 发布到托管源

git - 在 github 分支上重新设置

git - 如何忽略项目中的同名目录__pycache__?

powershell - 尝试在 heroku 上部署 Strapi 时出错。 grep 和 cut 无法识别

powershell - 如何从PowerShell调用svcutil exe?