【发布时间】:2019-03-24 18:13:32
【问题描述】:
我正在临时从池中删除代理,在代理所在的构建服务器上安装新软件,测试它是否工作,然后再次将代理添加到池中。
我想以编程方式执行此操作,或者使用 PowerShell,或者如果不可能,那么使用 C# 执行。
问题是我找不到任何可以帮助我执行此操作的文档,无论是通过 TFS REST API 还是通过 Visual Studio 附带的工具。
所以我特意问:
如何从构建池中删除命名代理以及 如何将命名代理添加回构建池?
我基本上想要进入 TFS 的 Web 管理和取消选中/选中池中的代理的相同功能。
当我尝试使用 starain-msft 提供的信息启用/禁用代理时,我收到以下错误:
Invoke-RestMethod :
404 - File or directory not found.
Server Error
后来我删除了大部分错误,因为我发现问题出在我公司的代理中。 在这里阅读:Azure DevOps Services REST API Reference
但我在 starain-msft 的帮助下让它工作了。
最终的解决方案是这样的:
Function TFSwebRequest {
param
(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory = $true)]
[string] $Uri,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory = $true)]
[string] $Method,
[ValidateNotNullOrEmpty()]
[string] $ContentType,
[ValidateNotNullOrEmpty()]
[string] $ContentBody,
[ValidateNotNullOrEmpty()]
[System.Net.WebHeaderCollection] $Headers
)
# Creating Webrequest from 'Uri'
$webRequest = [System.Net.HttpWebRequest]::CreateHttp($Uri)
$webRequest.UseDefaultCredentials = $true
$webRequest.Method = $Method
if ($Headers.Count -ne 0) {
$webRequest.Headers = $Headers
}
if (![string]::IsNullOrEmpty($ContentType)) {
$webRequest.ContentType = $ContentType
}
if (![string]::IsNullOrEmpty($ContentBody)) {
$Body = [byte[]][char[]]$ContentBody
$Stream = $webRequest.GetRequestStream();
$Stream.Write($Body, 0, $Body.Length);
}
# Get webresponse to a variable
try {
[System.Net.WebResponse]$webResponse = $webRequest.GetResponse()
}
catch {
$ErrorMessage = $_.Exception.Message
Write-Host "TFSwebRequest Failed = " $ErrorMessage -ForegroundColor Red
}
# Stream webresponse to a string
$webResponseStream = $webResponse.GetResponseStream()
$streamReader = New-Object System.IO.StreamReader $webResponseStream
$result = $streamReader.ReadToEnd() | ConvertFrom-Json
return ,$result
}
$agentUri = "http://teamfoundation:8080/tfs/Main/_apis/distributedtask/pools/$($poolID)/agents/$($agentID)?api-version=2.3-preview.1"
$contentBody = @"
{
"maxParallelism": 1,
"id": INSERTID,
"enabled": true #Or false
}
"@
$headers = New-Object System.Net.WebHeaderCollection
$headers.Add("X-HTTP-Method-Override", "PATCH")
TFSwebRequest -Uri $agentUri -Method "POST" -Headers $headers -ContentType "application/json" -ContentBody $contentBody
【问题讨论】:
-
您的构建代理是作为服务运行还是以交互模式运行?
-
我在答案中添加了 powershell 代码并禁用/启用构建代理 REST API,您可以检查一下。
-
你用我的解决方案解决了这个问题吗?
标签: c# rest powershell tfs-2015 build-agent