Getting Work Item Data in Powershell Through REST API
Here's a comprehensive look at extracting work item data with a REST API through Powershell.
Join the DZone community and get the full member experience.
Join For Freevsts and the latest versions of on-premise tfs have the ability to access data through rest api . this way to access tfs data is really convenient especially if used from powershell scripts, because you do not need any external dependency, except being able to issue rest requests with the invoke-restrequest cmdlet.
to simplify accessing your vsts account, you can enable alternate credentials, needed to issue a request with simple basic authentication . here is a powershell snippet that retrieve a work item with a given id.
$username = "alternateusername"
$password = "alternatepassword"
$basicauth = ("{0}:{1}" -f $username,$password)
$basicauth = [system.text.encoding]::utf8.getbytes($basicauth)
$basicauth = [system.convert]::tobase64string($basicauth)
$headers = @{authorization=("basic {0}" -f $basicauth)}
$result = invoke-restmethod -uri https://gianmariaricci.visualstudio.com/defaultcollection/_apis/wit/workitems/100?api-version=1.0 -headers $headers -method get
this is a simple code you can find everywhere on the internet, it is just a matter of converting username and password in base64 string and pass the result to invoke-restmethod with the –headers argument. the result is an object parsed from the json returned by the call . the nice aspect of powershell is that you can simply use the get-member cmdlet to list properties of returned object. here is the result of instruction
$result | get-member
figure 1 : result of the get-member shows all properties of returned object
in this situation, we can see the id of the work item and the rev property, but probably all the data we need is inside the fields property. if we simply write-output the $result.fields we got the full list of all the fields of the returned work item
figure 2: content of fields property of returned work item
any property can be accessed with standard dot notation (but pay attention to the dot in the name of the property, fields property is actually an hashset):
$closedby = $result.fields.'microsoft.vsts.common.closedby'
write-output "work item was closed by: $closedby"
thanks to powershell ise you can also use intellisense to have all the properties conveniently listed.
figure 3: intellisense on returned object
Published at DZone with permission of Ricci Gian Maria, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments