Need help with Powershell 7.4 Invoke-RestMethod error: 'Operation is not valid due to the current state of the object
Michael Cameron 6287
0
Reputation points
Hello
I'm trying to run an API Patch request, using Invoke-RestMethod, to update one item(email address) at the endpoint whilst looping through a dataset which has the item value to update and the parameter for the uri. I am, however, receiving an error of 'Operation is not valid due to the current state of object'.
My code is below:
$pair = "$($username):$($password)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$authValue = "$authentication $encodedCreds"
$headers = @{
Authorization = $authValue
ContentType = $contentType
}
#Get single table from dataset
$data = $dataSet.Tables[0]
foreach ($row in $data) {
# Access column values using $row.<ColumnName>
$par = $row.resource_id
$email = $row.email
$uri = $url + $par
$body = @{
"path" = $path
"op" = "AddOrReplaceById"
"value" = @{
"contactPointType" = "1"
"sortOrder" = 0
"additionalContactInfo" = @{
"eMail" = $email
}
}
}
$jsonBody = ConvertTo-JSON($body) -Depth 3
$restArgs = @{
Uri = $uri
Method = $method
Headers = $headers
Body = $jsonBody
}
# Send the JSON Data to the API
$response = Invoke-RestMethod @restArgs
$response
}
I'm a bit of a novice when it comes to writing scripts for API requests.
Any help would be greatly appreciated.
Thanks
Sign in to answer