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
2024-12-16T13:44:11.2+00:00

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

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,584 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.