How do I create a bug in TFS using REST API in PowerShell? - rest

I am trying to create a bug in TFS using REST API in PowerShell with the code below, but I'm unable to figure out how to fill the $Bug variable with names of those param's and data.
Param(
[string]$vstsAccount = "MyAccountName",
[string]$projectName = "ProjectName",
[string]$keepForever = "true",
[string]$user = "",
[string]$token = "Mytoken"
)
# 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/$($projectName)/_apis/wit/workitems/$Bug?api-version=2.2"
$result = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
I could find a sample for C# here, but not for PowerShell. Any help would be appreciated.
Cheers

You need to create a JSON body to use the REST API to create a work item in PowserShell, and the Content-Type should be application/json-patch+json, also use PATCH method. See Create a work item for details.
You can reference below sample PowerShell script to create a bug:
Param(
[string]$baseurl = "http://server:8080/tfs/DefaultCollection",
[string]$projectName = "ProjectName",
[string]$keepForever = "true",
[string]$user = "username",
[string]$token = "token"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
function CreateJsonBody
{
$value = #"
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "0925Bug"
},
{
"op": "add",
"path": "/fields/System.AreaPath",
"value": "LCScrum"
},
{
"op": "add",
"path": "/fields/System.IterationPath",
"value": "LCScrum\\Sprint 1"
},
{
"op": "add",
"path": "/fields/System.Tags",
"value": "Tag0921;Tag0926;Tag0927;Tag0928"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.Activity",
"value": "Development"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Scheduling.Effort",
"value": "8"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.ValueArea",
"value": "Business"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.Severity",
"value": "3 - Medium"
},
{
"op": "add",
"path": "/relations/-",
"value":
{
"rel": "System.LinkTypes.Dependency-Forward",
"url": "http://server:8080/tfs/DefaultCollection/_apis/wit/workItems/324",
"attributes":
{
"usage": "workItemLink",
"editable": false,
"enabled": true,
"acyclic": true,
"directional": true,
"singleTarget": true,
"topology": "dependency"
}
}
},
{
"op": "add",
"path": "/relations/-",
"value":
{
"rel": "System.LinkTypes.Hierarchy-Reverse",
"url": "http://server:8080/tfs/DefaultCollection/_apis/wit/workItems/58",
"attributes":
{
"usage": "workItemLink",
"editable": false,
"enabled": true,
"acyclic": true,
"directional": true,
"singleTarget": false,
"topology": "tree"
}
}
}
]
"#
return $value
}
$json = CreateJsonBody
$uri = "$baseurl/$($projectName)/_apis/wit/workitems/"+"$"+"bug?api-version=2.2"
Write-Host $uri
$result = Invoke-RestMethod -Uri $uri -Method Patch -Body $json -ContentType "application/json-patch+json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}

Related

Associate Work Item With Current Build and attach file to work item using powershell

How i can Associate Work Item With Current Build and attach file json to work item using powershell ? I use Azure Devops Service and i have this script:
$connectionToken="<my_token>"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$url= 'https://dev.azure.com/{organization}/{project_name}/_apis/wit/workitems/$Task?api-version=6.0'
$body=#"
[
{
"op": "add",
"path": "/fields/System.WorkItemType",
"value": "Risk"
},
{
"op": "add",
"path": "/fields/System.Title",
"value": "Test"
},
{
"op": "add",
"path": "/fields/System.Tags",
"value": "test"
},
{
"op": "add",
"path": "/fields/System.Description",
"value": "test"
},
{
"op": "add",
"path": "/fields/Mitigation",
"value": "test"
},
{
"op": "add",
"path": "/fields/Risk",
"value": "1 - High"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Build.IntegrationBuild",
"value": `"{value}`"}]"
}
]
"#
Write-Host "$url"
$response= Invoke-RestMethod -Uri $url -ContentType "application/json-patch+json" -Body $body -headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST
But link for associate with current build not work, and i cant find what i need to add to attach json file to work item from my Azure Pipeline
To attach a file, you have to upload the file (Upload a text file) and then add the link to your work item (Add an attachment): Attach a file and create new workitem
Microsoft.VSTS.Build.IntegrationBuild is just a field without any links. You have to add ArtifactLink link with Integrated in build type: Add build link to work item using REST API

Error while trying to create a release definition using Azure DevOps Rest API

I am using below script to create a release definition in Azure DveOps with a PowerShell script, but its failing with error message as below. Not sure where am giving incorrect details.
Invoke-RestMethod :
{"$id":"1","innerException":null,"message":"VS402903: The specified
value is not convertible to type ReleaseDefinition. Make sure it is
convertible to type ReleaseDefinition and try again."
Code snippet is:
Param(
[string]$organisation = "ORGNAME",
[string]$project = "PROJECTNAME",
[string]$keepForever = "true",
[string]$user = "userid",
[string]$token = "tokenID" )
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
Write-host $base64AuthInfo
$postresults = "https://vsrm.dev.azure.com/$organisation/$project/_apis/release/definitions?api-version=6.0"
Write-host $postresults
$body =
#"
{ "name": "New release pipeline ",
"comment": "test",
"definitionId": 860,
"description": "Create Release from PowerShell",
"artifacts": [],
"isDraft": false,
"reason": "Demo purpose",
"manualEnvironments": null,
"environmentsMetadata": null,
"properties": null,
"variables": null
"environments": [
{
"name": "PROD",
"preDeployApprovals": {
"approvals": [
{
"rank": 1,
"isAutomated": false,
"isNotificationOn": false,
"approver": {
"displayName": null,
"id": ""
},
"id": 0
}
]
},
"postDeployApprovals": {
"approvals": [
{
"rank": 1,
"isAutomated": true,
"isNotificationOn": false,
"id": 0
}
]
},
"deployPhases": [
{
"deploymentInput": {
"parallelExecution": {
"parallelExecutionType": "none"
},
"skipArtifactsDownload": false,
"artifactsDownloadInput": {},
"queueId": 391,
"demands": [],
"enableAccessToken": false,
"timeoutInMinutes": 0,
"jobCancelTimeoutInMinutes": 1,
"condition": "succeeded()",
"overrideInputs": {}
},
"rank": 1,
"phaseType": "agentBasedDeployment",
"name": "Run on agent",
"workflowTasks": []
}
],
"retentionPolicy": {
"daysToKeep": 30,
"releasesToKeep": 3,
"retainBuild": true
}
}
],
"path": "\\",
"releaseNameFormat": "Release",
"description": ""
}
"# | ConvertTo-Json -Depth 100
$result = Invoke-RestMethod -Uri $postresults -Method Post -Body $body -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
if ($result.count -eq 0)
{
throw "Unable to locate Release Definition Id $($definitionId)"
}
else
{
Write-host "Success!!!"
}
You have few issues in the json body:
The description exist twice.
You have missing , near the "variables": null.
You need to specify a valid id in the preDeployApprovals:
"approver": {
"displayName": null,
"id": "PUT-HERE-ID"
},
Add the above section also to the
You don't need to convert it again to json, remove the | ConvertTo-Json -Depth 100 from the code.

Invoke-RESTMethod PowerShell

I am trying to use the Invoke-Restmethod to call a set of API's, but it fails with the below error, i have also posted the same json format, can some let me know what could be wrong ?
### Ignore TLS/SSL errors
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
#Create URL string for Invoke-RestMethod
$urlsend = 'https://' + 'vrslcm-01a.corp.local/lcm/api/v1/' + '/login'
#Credential
$Username = "admin#localhost"
$password = "VMware1!"
$basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password"))
$headers = #{
"description"= "Testing Authentication"
}
$body = #{
$raw= '{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}'
"mode"= $raw
}
Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $body -ContentType 'application/json'
Here is the sample jSON which iam trying to invoke via powershell, it consists of the header and the body. I need to understand how we could call the same jSON POSTMAN example via the PowerShell Invoke-RestMethod
"item": [
{
"name": "authorization",
"description": "",
"item": [
{
"name": "Login",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"var response=JSON.parse(responseBody)",
"postman.setEnvironmentVariable(\"token\", response.token)"
]
}
}
],
"request": {
"url": "{{Server}}/lcm/api/v1/login",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}"
},
"description": ""
},
"response": []
},
{
"name": "Logout",
"request": {
"url": "{{Server}}/lcm/api/v1/logout",
"method": "POST",
"header": [
{
"key": "x-xenon-auth-token",
"value": "{{token}}",
"description": ""
}
],
"body": {},
"description": ""
},
"response": []
}
]
},
make $raw to a hashtable like
$raw = #{
username=$Username
password=$Password
}
add this hashtable to the $body hashtable
$body = #{
mode= $raw
}
but now it still is a hashtable the api cannot use. thus convert it to json like
$jsonBody = $body | ConvertTo-Json
using $jsonBody should then work when used like
Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $jsonBody -ContentType 'application/json'
Like the error states, the problem is your hash definition.
A null key is not allowed in a hash literal.
PowerShell tries to evaluate $raw as a hash table key. Since it hasn't been defined before it is null and fails because null is not allowed. Try it like this:
$raw= '{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}'
$body = #{
"mode"= $raw
}

Query MSGraph API with PowerShell Invoke-RestMethod does not return same amount of details as MSGraph Explorer

I used MSGraph Explorer and PowerShell Invoke-RestMethod to query the same MSGraph API, but MSGraph Explorer returns way more details than the PowerShell command. Could this be a permission issue or I missed something in the PowerShell command.
Here is the URI, it is to retrieve the audit log for a particular directory change.
https://graph.microsoft.com/beta/auditLogs/directoryAudits/Directory_029A8_49125229
This is the output from MSGraph Explorer:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#auditLogs/directoryAudits/$entity",
"id": "Directory_029A8_49125229",
"category": "Core Directory",
"correlationId": "d534994f-61f4-4015-8040-c16f728ec8b3",
"result": "success",
"resultReason": "",
"activityDisplayName": "Update user",
"activityDateTime": "2018-10-04T05:41:19.9668303Z",
"loggedByService": null,
"initiatedBy": {
"app": null,
"user": {
"id": "1f5c2159-f515-4cea-a99c-11c6ce1f7a5e",
"displayName": null,
"userPrincipalName": "tom-admin#contoso.onmicrosoft.com",
"ipAddress": "<null>"
}
},
"targetResources": [
{
"#odata.type": "#microsoft.graph.targetResourceUser",
"id": "498b3884-f723-444c-9c01-b75ec2c0ef08",
"displayName": null,
"userPrincipalName": "Tom.Real#contoso.com",
"modifiedProperties": [
{
"displayName": "AssignedLicense",
"oldValue": "[\"[SkuName=ENTERPRISEPACK, AccountId=cdc4b90d-7fa9-4a, SkuId=6f94b900, DisabledPlans=[]]\"]",
"newValue": "[]"
},
{
"displayName": "AssignedPlan",
"oldValue": "[{\"SubscribedPlanId\":..., \"ServicePlanId\":\"50e68c76-46c6-4674-81f9-75456511b170\"}]",
"newValue": "[{\"SubscribedPlanId\":... 50e68c76-46c6-4674-81f9-75456511b170\"}]"
},
{
"displayName": "Included Updated Properties",
"oldValue": null,
"newValue": "\"AssignedLicense, AssignedPlan\""
},
{
"displayName": "TargetId.UserType",
"oldValue": null,
"newValue": "\"Member\""
}
]
}
],
"additionalDetails": [
{
"key": "UserType",
"value": "Member"
}
]
}
This is the output from Invoke-RestMethod:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#auditLogs/directoryAudits/$entity",
"id": "Directory_029A8_49125229",
"category": "Core Directory",
"correlationId": "d534994f-61f4-4015-8040-c16f728ec8b3",
"result": "success",
"resultReason": "",
"activityDisplayName": "Update user",
"activityDateTime": "2018-10-04T05:41:19.9668303Z",
"loggedByService": null,
"initiatedBy": {
"app": null,
"user": {
"id": "1f5c2159-f515-4cea-a99c-11c6ce1f7a5e",
"displayName": null,
"userPrincipalName": "tom-admin#contoso.onmicrosoft.com",
"ipAddress": "\u003cnull\u003e"
}
},
"targetResources": [
{
"#odata.type": "#microsoft.graph.targetResourceUser",
"id": "498b3884-f723-444c-9c01-b75ec2c0ef08",
"displayName": null,
"userPrincipalName": "Tom.Real#contos.com",
"modifiedProperties": " "
}
],
"additionalDetails": [
{
"key": "UserType",
"value": "Member"
}
]
}
As you can see Invoke-RestMethod does not return any details under "additionalDetails".
This is my PowerShell script
Function GetAuthToken
{
param
(
[Parameter(Mandatory=$true)]
$TenantName
)
Import-Module Azure
$clientId = "ef9bcdf0-a675-4cd5-9ec3-fa549f9ee4cf"
$redirectUri = "https://RedirectURI.com"
$resourceAppIdURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$TenantName"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$Credential = Import-Clixml -Path "C:\MIMA\tom_admin_cred.xml"
$AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$AADCredential)
return $authResult
}
if($Version -eq $null) {$Version='Beta'}
#------Get the authorization token------#
$token = GetAuthToken -TenantName $tenant
#------Building Rest Api header with authorization token------#
$authHeader = #{
'Content-Type'='application\json'
'Authorization'=$token.CreateAuthorizationHeader()
}
$uri = "https://graph.microsoft.com/beta/auditlogs/directoryAudits/Directory_029A8_49125229"
$results = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get
$results |ConvertTo-Json
I believe everything is fine with your query and permissions, the results are different since for ConvertTo-Json cmdlet by default 2 levels of contained objects are included in the JSON representation.
So, if you want directoryAudit all properties to be included in result, Depth parameter needs to be specified explicitly, for example:
$results |ConvertTo-Json -Depth 3 #at least 3 levels for directoryAudit entry

Send Patch request through Rest API in powershell and TFS2015

Please find below request body I created in powershell with Patch method to create a bug in TFS. But not able to create a bug and gettign message that "TF401320: Rule Error for field Found In. Error code: Required, HasValues, InvalidEmpty.","typeName"..... I also attached error code here.
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$pass)))
function CreateJsonBody
{
$value = #"
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "TestBug"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.TCM.ReproSteps",
"value": "Our authorization logic needs to allow for users"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.Priority",
"value": "1"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.Severity",
"value": "2 - High"
}
]
"#
return $value
}
$json = CreateJsonBody
$uri = "http://xxx-xxxxx-006:8080/tfs/xxx/xxxxx/_apis/wit/workItems/"+"$"+"bug/?api-version=2.0"
Write-Host $uri
$result = Invoke-RestMethod -Uri $uri -Method Patch -Body $json -Credential
$credential -ContentType "application/json-patch+json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
But not getting response.
Below error is getting
{
"$id": "1",
"innerException": null,
"message": "TF401320: Rule Error for field Found In. Error code: Required, HasValues, InvalidEmpty.",
"typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.RuleValidationException, Microsoft.TeamFoundation.WorkItemTracking.Server, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"typeKey": "RuleValidationException",
"errorCode": 600171,
"eventId": 3200
}
Please help me. I already write code to create bugs for another account but not able to do here.