TFS 2015 API使用PowerShell从池中删除代理 [英] TFS 2015 API remove agent from pool with PowerShell

查看:113
本文介绍了TFS 2015 API使用PowerShell从池中删除代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在临时从池中删除代理,在代理所处的构建服务器上安装新软件,测试其是否正常运行,然后将代理再次添加到池中。



我想以编程方式执行此操作,或者使用PowerShell,或者如果不可能,请使用C#。



问题是我找不到任何文档可以通过TFS REST API或Visual Studio附带的工具来帮助我做到这一点。



所以我我专门问:



如何从构建池中删除命名代理,以及
如何将命名代理重新添加到构建池中? / p>

我基本上希望具有与TFS的网络管理相同的功能,并且取消选中/检查池中的代理。



当我尝试使用starain-msft提供的信息启用/禁用代理时,出现以下错误:

  Invoke-RestMethod: 
404-找不到文件或目录。
服务器错误

后来我删除了大部分错误,因为我发现问题出在在我公司的代理人中
在这里阅读: Azure DevOps Services REST API参考



但是我可以在starain-msft的帮助下使用它。



最终解决方案如下:

 函数TFSwebRequest {
参数

[ValidateNotNullOrEmpty()]
[参数(必填= $ true)]
[字符串] $ Uri,

[ValidateNotNullOrEmpty() ]
[Parameter(Mandatory = $ true)]
[string] $ Method,

[ValidateNotNullOrEmpty()]
[string] $ ContentType,

[ValidateNotNullOrEmpty()]
[string] $ ContentBody,

[ValidateNotNullOrEmpty()]
[System.Net.WebHeaderCollection] $ Headers


#从 Uri创建Webrequest
$ webRequest = [System.Net.HttpW ebRequest] :: 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);
}

#获取对变量
的webresponse尝试{
[System.Net.WebResponse] $ webResponse = $ webRequest.GetResponse()
}
catch {
$ ErrorMessage = $ _。Exception.Message
写主机 TFSwebRequest Failed = $ ErrorMessage -ForegroundColor Red
}

#流Web响应到字符串
$ webResponseStream = $ webResponse.GetResponseStream()
$ streamReader =新对象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,
已启用:true#或false
}
@

$ headers = New-Object System.Net.WebHeaderCollection
$ headers.Add( X-HTTP-Method-Override, PATCH)

TFSwebRequest -Uri $ agentUri-方法 POST -Headers $ headers -ContentType application / json -ContentBody $ contentBody


解决方案

代理的REST API池和代理:



获取代理池(请求方法:GET):

  http:// [TFS URL] / _ apis / distributedtask / pools?api-version = 2.3-preview.1 

获取代理池的代理(请求方法:GET):

  http:// [TFS URL ] / _ apis / distributedtask / pools / [pool i d] /agents?api-version=2.3-preview.1 

禁用/启用构建代理(请求方法:PATCH)

  http:// [TFS URL] / _ apis / distributedtask / pools / [pool id] / agents / [agent id]?api-version = 2.3-preview.1 

正文( Content-Type:应用程序/ json

  {
enabled:false ,
id:[代理ID],
maxParallelism:1
}

从座席池中删除座席(请求方法:DELETE):

  http:// [ Tfs URL] / _ apis / distributedtask / pools / [pool id] / agents / [agent id]?api-version = 2.3-preview.1 

调用REST API(PowerShell)的简单示例:

  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编码个人访问令牌(PAT)适当地
$ 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 =调用RestMethod -Uri $ uri -Method Get -ContentType application / json -Headers @ {Authorization =( Basic {0} -f $ base64AuthInfo)}

有关详细信息:使用PowerShell调用VSTS API



C#代码调用REST API:

  String MyURI = REST API URL; 
WebRequest WReq = WebRequest.Create(MyURI);
WReq.Credentials =
new NetworkCredential( [用户名], [密码], [域]);

WebResponse响应= WReq.GetResponse();
Console.WriteLine((((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();

StreamReader reader = new StreamReader(dataStream);

字符串responseFromServer = reader.ReadToEnd();

Console.WriteLine(responseFromServer);

另一方面,在将新软件安装到代理计算机后,您需要重新启动构建代理为了认出他们。


I'm working on removing an agent from a pool temporarily, install new software on the buildserver the agent is on, test that it works, and then add the agent to the pool again.

I would like to do that programmatically, either with PowerShell or if that isn't a possibility, then do it with C#.

The problem is that I can't find any documentation that can assist me on doing this, either through the TFS REST API or through the tools that come with Visual Studio.

So I'm specifically asking:

How do I remove a named agent from a build pool and how do I add a named agent back into the build pool?

I basically want the same functionality of going onto the web administration of TFS and unchecking/checking an agent in the pool.

When I try to enable/disable an agent with the information provided by starain-msft, I get the following error:

Invoke-RestMethod :
404 - File or directory not found.
Server Error

Later I removed much of the error, as I found out that issue lay in my company's proxy. Read here: Azure DevOps Services REST API Reference

But I got it to work with the help of starain-msft.

The final solution looks like this:

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

解决方案

REST API of the agent pool and agent:

Get agent pools (request method: GET):

http://[TFS URL]/_apis/distributedtask/pools?api-version=2.3-preview.1

Get agents of an agent pool (Request method: GET):

http://[TFS URL]/_apis/distributedtask/pools/[pool id]/agents?api-version=2.3-preview.1

Disable/enable build agent (Request method: PATCH)

http://[TFS URL]/_apis/distributedtask/pools/[pool id]/agents/[agent id]?api-version=2.3-preview.1

Body (Content-Type: application/json)

{
    "enabled": false,
    "id": [agent id],
    "maxParallelism": 1
}

Delete an agent from an agent pool (request method: DELETE):

http://[Tfs URL]/_apis/distributedtask/pools/[pool id]/agents/[agent id]?api-version=2.3-preview.1

Simple sample to call REST API (PowerShell):

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)}

For details: Calling VSTS APIs with PowerShell

C# code to call REST API:

String MyURI = "REST API URL";
WebRequest WReq = WebRequest.Create(MyURI);
WReq.Credentials =
    new NetworkCredential("[user name]", "[password]", "[domain]");

WebResponse response = WReq.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();

StreamReader reader = new StreamReader(dataStream);

string responseFromServer = reader.ReadToEnd();

Console.WriteLine(responseFromServer);

On the other hand, you need to restart the build agent after you install new software to the agent machine in order to recognize them.

这篇关于TFS 2015 API使用PowerShell从池中删除代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆