Not Able Remove Machine Role Using REST API

Hi Team,

I am using REST API to add role on target machine. However, I am not able to remove using same function.

PowerShell Code

# Define working variables
$octopusURL = ""
$octopusAPIKey = ""
$header = @{ "X-Octopus-ApiKey" = $octopusAPIKey }
$spaceName = "default"
$machineName = ""
$targetRole = "AppServer-3"
$targetRemoveRole = "AppServer-2"

    # Get space
    $space = (Invoke-RestMethod -Method Get -Uri "$octopusURL/api/spaces/all" -Headers $header) | Where-Object {$_.Name -eq $spaceName}

    # Get machine
    $machine = (Invoke-RestMethod -Method Get -Uri "$octopusURL/api/$($space.Id)/machines/all" -Headers $header) | Where-Object {$_.Name -eq $machineName}
    # Add target role
    $machine.roles += ($targetRole) # It is working 
    $machine.Roles.Remove($targetRemoveRole) # It is working 

    Invoke-RestMethod -Method Put -Uri "$octopusURL/api/$($space.Id)/machines/$($machine.Id)" -Body ($machine | ConvertTo-Json -Depth 10) -Headers $header
    Write-Host $_.Exception.Message


Exception calling "Remove" with "1" argument(s): "Collection was of a fixed size."

Hi Vivek,

Thank you for your question about using the API to remove machine roles.

It isn’t possible to directly remove entries from $machine.roles. You’ll instead need to populate a second array by iterating over $machine.roles and only copying the entries your want. You can then replace $machine.roles with the updated array. This would look something like the following pseudocode:

Create $updatedRoles
Iterate over $machine.roles
–> If the current item is to be kept, add it to $updatedRoles
–> If the current item is to be removed, don’t add it to $updatedRoles
Set $machine.roles to $updatedRoles

I hope this is helpful. Please let me know if you have any questions.

Best Regards,


Hi Charles,

Thanks for prompt reply. I have already tried the approach you have suggested , it is
just, I was looking for function which might delete it directly.

Anyways thanks for your immediate reply.


1 Like

This topic was automatically closed 31 days after the last reply. New replies are no longer allowed.