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

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.

Related

Invoke-WebRequest content ConvertFrom-Json: Conversion from JSON failed with error: Unexpected character encountered while parsing value (CR;LF)

I successfully sent an webrequest to a Website and got a responde:
$Uri = "https://URLXYZ"
$Method = "POST"
$Header = #{
"Accept" = "*/*";
"Connection" = "keep-alive";
"Accept-Encoding" = "gzip, deflate, br";
"Content-Type" = "text/json; charset=""UTF-8"""
}
$Body = #"
{
"Items": [
{
"Type": "XX",
"Value": "YY",
}
],
"TypeId": XY,
"LiveConditions": []
}
"#
$webrequest = Invoke-WebRequest -Uri $Uri -Body $Body -Headers $Header -Method $Method
Now, I am trying to convert it from JSON without success:
$webrequest.Content | ConvertFrom-Json
ConvertFrom-Json: Conversion from JSON failed with error: Unexpected character encountered while parsing value: . Path '', line 0, position 0.
When I copy the output ($webrequest.Content) to Notepad++ I can see a carriage return (CR) and line feed (LF):
$webrequest.Content
[{"MailG":[{"DisplayName":{"7":"Worker","9":"Person"},"Mails":"max.mustermann#gmai.com;"}],"ResultCount":1,"Rows":[{"ElementGroups":[{"ObjectContainer":{"Id":55
6677889900,"UID":"1122334455","Info":[],"PreCalculatedSelectedProperties":{"11":"Mustermann","22":"","33":"StreetName","44":"","55":"max.mustermann#gmai.com","66":"","77":"Berlin","88":"","99":"Max Mustermann","00":"+49 00 000 000","111":"userid","222":"xyz","333":"company","444":"1122334455","555":"roomnumber","666":"Germany","777":"Team","888":"+49 000 0 00 0","999":"Max","000":""},"TID":5,"RuleConditionPartResults":{"1448925":false,"1448926":false,"1448927":false,"1448928":false,"1448929":false,"1448930":false,"1448931":false,"1448932":false,"1448933":false,"1448934":false,"1448935":false,"1448936":false,"1448937":false,"1448938":false,"1448939":false,"1448940":false,"1448941":false,"1448942":false},"Img":{"3714":["picture"]},"Parents":[],"Childs":[],"UpObjects":0,"Down":0,"LinkCount":0,"FootObject":{},"BoxIds":[],"DisplayValue":"Max Mustermann","Key":"1122334455"},"Columns":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}],"Blank":{},"Score":0.0,"SInd":0}],"Page":0,"TID":5}]
This is unexpected cause the CR;LF is e.g. in the middle of an email address.
If the response is longer, there are multiple CR;LF within the content of the webrequest.
The $webrequest.content is TypeName: System.String
If I manually remove the CR;CF in Notepad++ and PrettyPrint it is working:
[
{
"MailG": [
{
"DisplayName": {
"7": "Worker",
"9": "Person"
},
"Mails": "max.mustermann#gmai.com;"
}
],
"ResultCount": 1,
"Rows": [
{
"ElementGroups": [
{
"ObjectContainer": {
"Id": 556677889900,
"UID": "1122334455",
"Info": [],
"PreCalculatedSelectedProperties": {
"11": "Mustermann",
"22": "",
"33": "StreetName",
"44": "",
"55": "max.mustermann#gmai.com",
"66": "",
"77": "Berlin",
"88": "",
"99": "Max Mustermann",
"00": "+49 00 000 000",
"111": "userid",
"222": "xyz",
"333": "company",
"444": "1122334455",
"555": "roomnumber",
"666": "Germany",
"777": "Team",
"888": "+49 000 0 00 0",
"999": "Max",
"000": ""
},
"TID": 5,
"RuleConditionPartResults": {
"1448925": false,
"1448926": false,
"1448927": false,
"1448928": false,
"1448929": false,
"1448930": false,
"1448931": false,
"1448932": false,
"1448933": false,
"1448934": false,
"1448935": false,
"1448936": false,
"1448937": false,
"1448938": false,
"1448939": false,
"1448940": false,
"1448941": false,
"1448942": false
},
"Img": {
"3714": [
"picture"
]
},
"Parents": [],
"Childs": [],
"UpObjects": 0,
"Down": 0,
"LinkCount": 0,
"FootObject": {},
"BoxIds": [],
"DisplayValue": "Max Mustermann",
"Key": "1122334455"
},
"Columns": [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17
]
}
],
"Blank": {},
"Score": 0.0,
"SInd": 0
}
],
"Page": 0,
"TID": 5
}
]
I already tried to convert it or even replace the CR;LF it in PowerShell without success.
The only workaround I found is to write the content to a .txt-file and read it again.
$webrequest.Content | Out-File "C:\Temp\WebRequestTemp.txt"
$json = Get-Content "C:\Temp\WebRequestTemp.txt" | ConvertFrom-Json
Afterwards I was able to convert it from JSON and work with the data.
Why can I not directly convert it from JSON as usual?
To help you with a more detailed answer. It is useful to share the contents of the web response. But maybe the line below will solve your problem.
$jsonCorrected = [Text.Encoding]::UTF8.GetString([Text.Encoding]::GetEncoding(28591).GetBytes(($webrequest.Content)))
I had a similar issue, and the issue was there was an unknown invisible character at the beginning of the content block. This character was "U+FEFF".
I managed to get it to be replaced by doing $webrequest.Content -replace '\uFEFF' | ConvertFrom-Json
I hope this works for anyone else too.

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

Powershell script for building CI/CD for Azure Data factory

I'm planning to build Continous integration and Deployment for Azure Data factory using PowerShell. So all the build and release process which can be done using VSTS has to be done using Powershell. If anyone can share any links or powershell scripts it would be helpful. Thanks
If you mean create build/release definition through PowerShell, you can do it through VSTS REST with PowerShell, simple code:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "","{personal access token}")))
$body='{
"variables": {
"system.debug": {
"value": "false",
"allowOverride": true
}
},
"retentionRules": [
{
"branches": [
"+refs/heads/*"
],
"artifacts": [],
"artifactTypesToDelete": [
"FilePath",
"SymbolStore"
],
"daysToKeep": 10,
"minimumToKeep": 1,
"deleteBuildRecord": true,
"deleteTestResults": true
}
],
"properties": {},
"tags": [],
"jobAuthorizationScope": "projectCollection",
"jobTimeoutInMinutes": 60,
"jobCancelTimeoutInMinutes": 5,
"process": {
"phases": [
{
"steps": [
{
"environment": {},
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
"displayName": "Azure PowerShell script: FilePath",
"timeoutInMinutes": 0,
"condition": "succeeded()",
"task": {
"id": "72a1931b-effb-4d2e-8fd8-f8472a07cb62",
"versionSpec": "2.*",
"definitionType": "task"
},
"inputs": {
"ConnectedServiceNameSelector": "ConnectedServiceNameARM",
"ConnectedServiceName": "",
"ConnectedServiceNameARM": "aad18bbf-0333-41bf-99ea-674181d17ada",
"ScriptType": "FilePath",
"ScriptPath": "$/Scrum2015/ClassLibraryA/dbtest.ps1",
"Inline": "# You can write your azure powershell scripts inline here. \n# You can also pass predefined and custom variables to this script using arguments",
"ScriptArguments": "",
"TargetAzurePs": "LatestVersion",
"CustomTargetAzurePs": ""
}
}
],
"name": "Phase 1",
"refName": "Phase_1",
"condition": "succeeded()",
"target": {
"executionOptions": {
"type": 0
},
"allowScriptsAuthAccessOption": false,
"type": 1
},
"jobAuthorizationScope": "projectCollection",
"jobCancelTimeoutInMinutes": 1
}
],
"type": 1
},
"repository": {
"properties": {
"cleanOptions": "0",
"tfvcMapping": "{\"mappings\":[{\"serverPath\":\"$/Scrum2015/ClassLibraryA\",\"mappingType\":\"map\",\"localPath\":\"\\\\\"},{\"serverPath\":\"$/Scrum2015/ClassLibraryA/VS2010UltimTrial.iso\",\"mappingType\":\"cloak\",\"localPath\":\"\"},{\"serverPath\":\"$/Scrum2015/ClassLibraryA/tools\",\"mappingType\":\"cloak\",\"localPath\":\"\"}]}",
"labelSources": "0",
"labelSourcesFormat": "$(build.buildNumber)"
},
"id": "$/",
"type": "TfsVersionControl",
"name": "Scrum2015",
"defaultBranch": "$/Scrum2015/ClassLibraryA",
"rootFolder": "$/Scrum2015",
"clean": "false",
"checkoutSubmodules": false
},
"processParameters": {},
"quality": "definition",
"drafts": [],
"queue": {
"id": 179
},
"name": "PowerShellRest2VNext",
"path": "\\",
"type": "build",
"queueStatus": "enabled"
}'
$result = Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $body
Note, you can create a sample build/release definition, then get it through VSTS REST API to get JSON content.
A blog that can help you: VSTS/TFS REST API: The basics and working with builds and releases
If you mean custom build/release task, you can refer to Add a build or release task, for powershell, change execution like this:
"execution": {
"PowerShell3": {
"target": "Hello.ps1",
"argumentFormat": ""
}
}
Regarding deploy azure data factory, you can refer to: How to deploy Azure Data Factory pipeline and its dependencies programatically using PowerShell (Do not need to call Login-AzureRMAccount and Select-AzureRMSubscrition, just add Azure PowerShell task to build/release definition).
A 3rd extension: Azure Data Factory

Error managing taskgroups using the TFS api and builtin OAuth System.Accesstoken

I've created a powershell script that does some updating of taskgroups that we need in our company. I do this by calling the route "/_apis/distributedtask/taskgroups".
This script works well when I use a personal access token from myself. However, I need it to be run by a build agent as part of a release process.
To manage this I have enabled "Allow scripts to access OAuth token" as outlined in
VSTS - allow Scripts to Access OAuth Token in Release Managment
I have then in my powershell script used the logic outlined here
https://learn.microsoft.com/sv-se/vsts/build-release/actions/scripts/powershell#oauth
to gain access to the token and include it in my api calls to the TFS api. I am successfull in retrieving the taskgroups this way, but when I try to update one I get
[error]Invoke-RestMethod : TF400813: Resource not available for
anonymous access. Client authentication required.
To exclude permisson problems I have given the build agent account "Project administrator" persmissions as well as "Build administrator" and "Release administrator". Any suggestions?
It appears that OAuth token is not registered for the server.
Please refer to slautebach's solution in this thread for troubleshooting:
It appears that during our upgrade TFS did not register a OAuth token
for the server.
The SQL recommend to execute was: using the FQDN (ie
tfs-server.doman.com)
EXEC prc_SetRegistryValue 1,'#\Configuration\OAuth\TrustedIssuers\tfs-sever.domain.com\','Microsoft.TeamFoundation.Framework.Server.OAuth.ClientAuthTokenValidator'
This prevented all users from logging in after a TFS server reboot. We
then tried with just the server name (ie tfs-server)
EXEC prc_SetRegistryValue 1,'#\Configuration\OAuth\TrustedIssuers\tfs-server\','Microsoft.TeamFoundation.Framework.Server.OAuth.ClientAuthTokenValidator'
This than allowed normal user login and the builds to finally work
after a server reboot and re-registering all the build agent.
If that still not work, as a workaround you can use basic authorization to do that:
Below PowerShell script works for me:
Param(
[string]$baseurl = "http://server:8080/tfs/DefaultCollection",
[string]$projectName = "ProjectName",
[string]$keepForever = "true",
[string]$user = "username",
[string]$token = "password"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
#Need to change revision every time
function CreateJsonBody
{
$value = #"
{
"tasks": [
{
"displayName": "PowerShell Script",
"alwaysRun": false,
"continueOnError": false,
"condition": "succeeded()",
"enabled": true,
"timeoutInMinutes": 0,
"inputs": {
"scriptType": "filePath",
"scriptName": "$/TFVC-Scrum2018/ConsoleApp1/PS/0129-GetIISsites.ps1",
"arguments": "",
"workingFolder": "",
"inlineScript": "# You can write your powershell scripts inline here. \n# You can also pass predefined and custom variables to this scripts using arguments\n\n Write-Host \"Hello World\"",
"failOnStandardError": "true"
},
"task": {
"id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1",
"versionSpec": "1.*",
"definitionType": "task"
}
},
{
"displayName": "PowerShell Script",
"alwaysRun": false,
"continueOnError": false,
"condition": "succeeded()",
"enabled": true,
"timeoutInMinutes": 0,
"inputs": {
"scriptType": "filePath",
"scriptName": "$/TFVC-Scrum2018/ConsoleApp1/PS/0129.ps1",
"arguments": "",
"workingFolder": "",
"inlineScript": "# You can write your powershell scripts inline here. \n# You can also pass predefined and custom variables to this scripts using arguments\n\n Write-Host \"Hello World\"",
"failOnStandardError": "true"
},
"task": {
"id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1",
"versionSpec": "1.*",
"definitionType": "task"
}
}
],
"visibility": [
"Build",
"Release"
],
"runsOn": [
"Agent",
"DeploymentGroup"
],
"owner": "d122de31-36a7-415c-aa42-b6d09295d5a0",
"revision": 2,
"createdBy": {
"id": "d122de31-36a7-415c-aa42-b6d09295d5a0",
"displayName": "xxx",
"uniqueName": "xxx"
},
"createdOn": "2018-02-02T07:17:45.25Z",
"modifiedBy": {
"id": "d122de31-36a7-415c-aa42-b6d09295d5a0",
"displayName": "xxx",
"uniqueName": "xxx"
},
"modifiedOn": "2018-02-02T07:17:45.25Z",
"id": "4c8c1d32-52bc-492e-ba4d-c9b1b363bcdf",
"name": "0203",
"version": {
"major": 1,
"minor": 0,
"patch": 0,
"isTest": false
},
"serverOwned": false,
"contentsUploaded": true,
"iconUrl": "/tfs/_static/tfs/Dev16.M122.5/_content/icon-meta-task.png",
"hostType": null,
"packageType": "",
"packageLocation": "",
"sourceLocation": "",
"minimumAgentVersion": "*",
"friendlyName": "0203",
"description": "test0203",
"category": "Build",
"helpMarkDown": "",
"definitionType": "metaTask",
"author": "xxx",
"demands": [],
"groups": [
{
"name": "PowerShell Script",
"displayName": "PowerShell Script",
"isExpanded": true,
"visibleRule": ""
},
{
"name": "PowerShell Script",
"displayName": "PowerShell Script",
"isExpanded": true,
"visibleRule": ""
}
],
"inputs": [],
"satisfies": [],
"sourceDefinitions": [],
"dataSourceBindings": [],
"instanceNameFormat": "Task group: 0203 ",
"execution": {}
}
"#
return $value
}
$json = CreateJsonBody
$uri = "$baseurl/$($projectName)/_apis/distributedtask/taskgroups?api-version=4.0-preview.1"
Write-Host $uri
$result = Invoke-RestMethod -Uri $uri -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
It was actually a permission issue. I was assuming that the OAuth token being used would be from the user that the build agent was running as, but this was not the case.
I resolved this by giving 'Project Collection Build Service' user "Edit task group" permissions on each collections task groups.

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

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