Download secure file with PowerShell Download secure file with PowerShell powershell powershell

Download secure file with PowerShell


I was able to download Secure Files using a REST API, the task's Access Token, and an Accept header for application/octet-stream. I enabled "Allow scripts to access the OAuth token". Here my task.json is using a secureFile named "SecureFile."

$secFileId = Get-VstsInput -Name SecureFile -Require$secTicket = Get-VstsSecureFileTicket -Id $secFileId$secName = Get-VstsSecureFileName -Id $secFileId$tempDirectory = Get-VstsTaskVariable -Name "Agent.TempDirectory" -Require$collectionUrl = Get-VstsTaskVariable -Name "System.TeamFoundationCollectionUri" -Require$project = Get-VstsTaskVariable -Name "System.TeamProject" -Require$filePath = Join-Path $tempDirectory $secName$token= Get-VstsTaskVariable -Name "System.AccessToken" -Require$user = Get-VstsTaskVariable -Name "Release.RequestedForId" -Require$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User, $token)))$headers = @{    Authorization=("Basic {0}" -f $base64AuthInfo)    Accept="application/octet-stream"} Invoke-RestMethod -Uri "$($collectionUrl)$project/_apis/distributedtask/securefiles/$($secFileId)?ticket=$($secTicket)&download=true&api-version=5.0-preview.1" -Headers $headers -OutFile $filePath

I am using "$(Build.QueuedById)" to get the user id in build tasks, but honestly I don't think it matters what string you use there.

If you don't have the Accept header, you'll get JSON metadata back for the file you're attempting to download.

Unfortunately I cobbled this together from other SO posts and the github issues pages; I can't find anywhere official that documents the URL I'm using there.


There has no such REST API to download secure file, but you can use Download secure file task for assistants.

And since the secure file only exist in temporary location during build, you should download the secure file by Download secure file task firstly, and copy the secure file to another directory secondly:

1. Download secure file

You can add a Download secure file task (for VSTS) and specify the filename to download.

Note: since the task is not available for TFS, you can install the similar task like Download Secure File extension for your TFS account.

2. Copy secure file to another directory

Such as copy the secure file to $(Build.ArtifactStagingDirectory), you can use PowerShell script:

Copy-Item -Path $(Agent.WorkFolder)\_temp\filename -Destination $(Build.ArtifactStagingDirectory)

Or use Copy Files task to copy the secure file to $(Build.ArtifactStagingDirectory).

BTW: