Azure-Devops remove user from projectContributor via Rest API - azure-devops

Using PowerShell I am attempting to remove a user from groupType projectContributor so I can move him to the Project Team. I can accomplish the add to the Project Team however I have tried everything I can to remove this users entitlement using a PATCH without success. FYI to avoid comments, OrgUrl, projectId and userId are being passed.
$b= #"
[
{
"op": "remove",
"path": "/projectEntitlements",
"value": {
"projectRef": {
"id": "$projectID"
},
"group": {
"groupType": "projectContributor"
}
}
}
]
"#
$uri = "$orgURL/_apis/userentitlements/$userId`?api-version=5.1-preview.2"
Invoke-RestMethod -Uri $uri -ContentType "application/json-patch+json" -Body $b -Method PATCH -Headers #{ Authorization = ("Basic {0}" -f $base64AuthInfo)}
The error I am getting is this:
projectId","typeName":"System.ArgumentException, mscorlib","typeKey":"ArgumentException","errorCode":0,"eventId":0}
At line:20 char:1
+ Invoke-RestMethod -Uri $uri -ContentType "application/json-patch+json ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Any help / examples are appreciated.
I have gone through all the API documentation for Azure DevOps API.

I got the same error using User Entitlement rest api.
It worked for me with Remove Member From Group rest api.
DELETE https://vsaex.dev.azure.com/{organization}/_apis/GroupEntitlements/{groupId}/members/{memberId}?api-version=5.1-preview.1
When a user is added to a project as Project Contributors. This user will be added to group [ProjectName]\\Contributors of this Project.
You can then use Group List rest api to get the group id of [ProjectName]\\Contributors. The {memberId} of above Remove Member From Group api is user's userId. Then you can just call above api to remove the user from the project contributors group.

Please try this:
$b= #"
[
{
"op": "remove",
"path": "/projectEntitlements/$projectID",
"value": {
"projectRef": {
"id": "$projectID"
},
"group": {
"groupType": "projectContributor"
}
}
}
]
"#
And since you are removing value under this path I'm not sure if you need value, so this should provide you the same:
$b= #"
[
{
"op": "remove",
"path": "/projectEntitlements/$projectID",
"value": ""
}
]
"#

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

update/create TFS Server variable group using REST API with powershell gives object reference not set

Allright i have been fiddling with this for a few hours now and i can't seem to find any resources online or solve the issue.
Looking at the api documentation at https://learn.microsoft.com/en-us/rest/api/azure/devops/distributedtask/variablegroups/get?view=azure-devops-rest-6.0
I can get info regarding the variable group that i created as a test:
$invRestMethParams = #{
Uri = "https://xxx.xxx.nl/tfs/DefaultCollection/$($project)/_apis/distributedtask/variablegroups/242/?api-version=6.0-preview.2"
Method = 'GET'
ContentType = 'application/json'
}
Invoke-RestMethod #invRestMethParams -UseDefaultCredentials
I then convert the result to json to get the required values for the PUT or POST to update or create:
{
"variables": {
"check": {
"value": "value"
}
},
"id": 242,
"type": "Vsts",
"name": "TestUpdate",
"description": "",
"isShared": false,
"variableGroupProjectReferences": [
{
"projectReference": "#{id=0add8cd8-0fc8-4aca-8eb4-164cd8d09c9d; name=AutoUpdateVariableGroups}",
"name": "TestUpdate",
"description": ""
}
]
}
The documentation states the update url is:
PUT https://{instance}/{collection}/_apis/distributedtask/variablegroups/{groupId}?api-version=6.0-preview.2
With request body having the above json values (without the ID as this is in the URI). So my update json becomes:
$body = #"
{
"variables": {
"checkupdated": {
"value": "valueupdated"
}
},
"type": "Vsts",
"name": "TestUpdate",
"description": "",
"isShared": false,
"variableGroupProjectReferences": [
{
"projectReference": "#{id=0add8cd8-0fc8-4aca-8eb4-164cd8d09c9d; name=AutoUpdateVariableGroups}",
"name": "TestUpdate",
"description": ""
}
]
}
"#
i convert it from json to see if its valid (no errors).
and use it in my PUT request:
$invRestMethParams = #{
Uri = "https://xxx.xxx.nl/tfs/DefaultCollection/_apis/distributedtask/variablegroups/242/?&api-version=6.0-preview.2"
Method = 'PUT'
ContentType = 'application/json'
Body = $body
}
Invoke-RestMethod #invRestMethParams -UseDefaultCredentials
The error i receive is:
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Object reference not set to an instance of an object.","typeName":"System.NullReferenceException, mscorlib","typeKey":"NullReferenceException","errorCode":0,"eventId":0}
At line:32 char:1
+ Invoke-RestMethod #invRestMethParams -UseDefaultCredentials
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Not sure how to troubleshoot this, does anyone know how to fix this issue? seems i am forgetting a value but im kinda lost as to what is the issue here.
From your script, it seems that it has issue with your request body.
In projectReference field, you need to use , to replace the ; and you need to modify the format.
"projectReference": {"id":"projectID", "name":"projectname"},
Refer to my sample:
$JSON = #"
{
"variables": {
"checkupdate": {
"value": "vaslueupdate"
}
},
"type": "Vsts",
"name": "AA",
"description": "",
"isShared": false,
"variableGroupProjectReferences": [
{
"projectReference": {"id":"108e4d7c-0bf3-4940-80da-4793f83def92", "name":"kevin1012"},
"name": "AA",
"description": ""
}
]
}
"#

Format for json via powershell

I'm trying to use powershell to send json to DevOps API. I can't seem to figure out how to properly format this so powershell will take it. I keep getting this error. Any advice? I'm able to use the same json in Postman without any issues. Thanks
$URI= "https://vsaex.dev.azure.com/$ClientOrg/_apis/userentitlements?api-version=5.1-preview.2" $AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($PAT)")) }
Invoke-RestMethod -uri $URI -Method POST -Headers $AzureDevOpsAuthenicationHeader -Body $a -ContentType "application/json"
$a= ConvertFrom-JSON #'
{
"accessLevel": {
"licensingSource": "msdn",
"accountLicenseType": "enterprise",
"msdnLicenseType": "enterprise"
},
"extensions": [
{
"id": "ms.feed"
}
],
"user": {
"principalName": "email#mail.com",
"subjectKind": "user"
},
"projectEntitlements": [
{
"group": {
"groupType": "projectAdministrator"
},
"projectRef": {
"id": "0685a10e"
}
}
]
}
'#
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Value cannot be null.\r\nParameter name: userEntitlement","typeName":"System.ArgumentNullException,
mscorlib","typeKey":"ArgumentNullException","errorCode":0,"eventId":0}
At line:4 char:1
+ Invoke-RestMethod -uri $URI -Method POST -Headers $AzureDevOpsAutheni ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Your body should be the JSON string itself and not an object built from the JSON.
$a= #'
{
"accessLevel": {
"licensingSource": "msdn",
"accountLicenseType": "enterprise",
"msdnLicenseType": "enterprise"
},
"extensions": [
{
"id": "ms.feed"
}
],
"user": {
"principalName": "email#mail.com",
"subjectKind": "user"
},
"projectEntitlements": [
{
"group": {
"groupType": "projectAdministrator"
},
"projectRef": {
"id": "0685a10e"
}
}
]
}
'#
Invoke-RestMethod -uri $URI -Method POST -Headers $AzureDevOpsAuthenicationHeader -Body $a -ContentType "application/json"

Directory_ExpiredPageToken when looping through response without delay

I am accessing Microsoft Graph using PowerShell which is working like a charm, except paging.
From time to time I get Directory_ExpiredPageToken errors. The errors are mostly gone if I set a 1 sec delay between the requests.
$ReturnObject = #()
while ($Uri.Length -gt 0) {
Add-TraceLine -Type DEBUG -Text "Calling '$($Uri)'"
$Response = Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
$ReturnObject += $Response
if ($Response.'#odata.nextlink') {
$Uri = $Response.'#odata.nextlink'
#Delay needed, otherwise Directory_ExpiredPageToken errors occured
Start-Sleep -Milliseconds 1000
}
else {
$Uri = $null
}
}
Any idea whats going on here?
The delay is a workaround to get the workflow running which is using this module. But I want to get rid of it because of performance reason.
EDIT:
This is a JSON response simplified (value is not only one object, but an array) and changed a little bit because of privacy/security reasons:
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(department,displayName,ext2j5y6eqq_linkeduser,givenName,id,jobTitle,mail,mailNickname,surname,userPrincipalName)",
"#odata.nextLink": "https://graph.microsoft.com/v1.0/users?$filter=userType+eq+%27Guest%27\u0026$select=department%2cdisplayName%2cext2j5y6eqq_linkeduser%2cgivenName%2cid%2cjobTitle%2cmail%2cmailNickname%2csurname%2cuserPrincipalName\u0026$skiptoken=RFNwdAkAAQAAAAAAAAAAFAAAADzX_JYCsThFmyry6_Ndz8kBAAAAAAAAAAAAAAAAAAAXMS4yLjg0MC4xMTM1NTYuMS40LjIzMzECAAAAAAABJruiMN_CtUmk63sXDRMMdg",
"value": [
{
"id": "80f7fa19-2669-470d-86ac-ee4c052a5186",
"department": null,
"displayName": "XC Admin",
"givenName": "XC",
"jobTitle": null,
"mail": null,
"mailNickname": "xcadmin",
"surname": "Admin",
"userPrincipalName": "xcadmin#domain.onmicrosoft.com"
}
]
}
EDIT:
This is the error response
+ ERROR { throw $Line }
+ ~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (11.04.2018-06:5...
}
}
}:String) [], RuntimeException
+ FullyQualifiedErrorId : 11.04.2018-06:50:13: <ERROR> - Get-User: {
"error": {
"code": "Directory_ExpiredPageToken",
"message": "The specified page token value has expired and can no longer be included in your request.",
"innerError": {
"request-id": "13ecca81-2d8c-4d0f-a58e-4a9cdd72e100",
"date": "2018-04-11T04:50:15"
}
}
}

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.