可以从基于PowerShell的VSTS构建任务使用ExtensionDataService吗?

时间:2016-12-21 00:27:47

标签: powershell azure-devops azure-pipelines azure-pipelines-build-task azure-devops-rest-api

我为Visual Studio Team Services(以前称为Visual Studio Online)创建了基于PowerShell的构建任务。我已经实现了我需要的大部分功能,但是对于最后一点功能,我需要能够在构建之间保留少量数据。

ExtensionDataService似乎正是我想要的(特别是setValue和getValue方法),但the documentation and examples I have found用于基于node.js的构建任务:

    VSS.getService(VSS.ServiceIds.ExtensionData).then(function(dataService) {
    // Set a user-scoped preference
    dataService.setValue("pref1", 12345, {scopeType: "User"}).then(function(value) {
        console.log("User preference value is " + value);
    });

上一页还有调用REST API的部分示例,但在尝试使用它来保存或检索值时,我遇到了404错误:

GET _apis/ExtensionManagement/InstalledExtensions/{publisherName}/{extensionName}/Data/Scopes/User/Me/Collections/%24settings/Documents
{
    "id": "myKey",
    "__etag": -1,
    "value": "myValue"
}

PowerShell可以通过使用库或直接调用REST API来访问ExtensionDataService吗?

1 个答案:

答案 0 :(得分:1)

您可以通过PowerShell调用REST API。

设置值(设置请求):

 https://[vsts name].extmgmt.visualstudio.com/_apis/ExtensionManagement/InstalledExtensions/{publisherName}/{extension id}/Data/Scopes/User/Me/Collections/%24settings/Documents?api-version=3.1-preview.1

正文(内容类型: application / json

{
  "id": "myKey",
  "__etag": -1,
  "value": "myValue"
}

获取价值(获取请求):

https://[vsts name].extmgmt.visualstudio.com/_apis/ExtensionManagement/InstalledExtensions/{publisherName}/{extension id}/Data/Scopes/User/Me/Collections/%24settings/Documents/mykey?api-version=3.1-preview.1

发布商名称和扩展名ID可以在包json文件中获取(例如vss-extension.json)

关于通过PowerShell调用REST API,您可以参考这篇文章:Calling VSTS APIs with PowerShell

调用REST API的简单示例:

Param(
   [string]$vstsAccount = "<VSTS-ACCOUNT-NAME>",
   [string]$projectName = "<PROJECT-NAME>",
   [string]$buildNumber = "<BUILD-NUMBER>",
   [string]$keepForever = "true",
   [string]$user = "",
   [string]$token = "<PERSONAL-ACCESS-TOKEN>"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$uri = "https://$($vstsAccount).visualstudio.com/DefaultCollection/$($projectName)/_apis/build/builds?api-version=2.0&buildNumber=$($buildNumber)"

$result = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

用于获取基本URL的PowerShell脚本:

Function GetURL{
param([string]$url)
$regex=New-Object System.Text.RegularExpressions.Regex("https:\/\/(.*).visualstudio.com")
$match=$regex.Match($url)
 if($match.Success)
    {
        $vstsAccount=$match.Groups[1]
        $resultURL="https://$vstsAccount.extmgmt.visualstudio.com"
    }
}
GetURL "https://codetiger.visualstudio.com/"