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

Can ExtensionDataService be used from a PowerShell-based VSTS build task?

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

ExtensionDataService seems like exactly what I want (in particular, the setValue and getValue methods), but 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 访问 ExtensionDataService,方法是使用库或直接调用 REST API?

您可以通过 PowerShell 调用 REST API。

设置值(Put请求):

 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调用RESTAPI,可以参考这篇文章: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)}

获取基础的PowerShell脚本URL:

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/"