Home > Enterprise >  How to alternate actions on variables in an array (one of two things for every other variable)
How to alternate actions on variables in an array (one of two things for every other variable)

Time:01-22

I've been tasked with creating an API script in Powershell that will reach out for a record, change one parameter to either A or B (alternating), write the record back, then move to the next record. The part I can't get my caffeine-deprived brain around is how to perform the alternation. It basically just needs to go back and forth so approximately 50% get A and 50% get B. Any thoughts on how to accomplish this? I feel this should be simple, but I'm just not able to figure it out at the moment.

$APIURL = "https://$Server.$ServerDomain/api/v1"
$EndpointURL = $APIURL "/computer/?q=deleted:false"
$EndpointList = Invoke-RestMethod -Uri $EndpointURL -Method Get -Header @{"X-Auth-Token" = $apiKey}

# Set the new policy ID to use A on the first variable, then B on the next, then back to A, and so on
#$NewPolicyId = A
#$NewPolicyId = B

# Format the change and send it back to the server for writing
$SpecificEndpoint.policyId = $NewPolicyId
$POST_URL = "$APIURL/computer/"   $SpecificEndpoint.id
$json = $SpecificEndpoint | ConvertTo-Json
Invoke-RestMethod -Uri $POST_URL -Method Post -Header @{"X-Auth-Token" = $apiKey} -Body $json -ContentType "application/json"```

CodePudding user response:

All you need is a simple 2-item array containing the policy names, and a variable to keep track of what you picked last time:

$policies = @('A', 'B')
$pickSecond = $false

foreach($SpecificEndpoint in $EndpointList)
{
    # pick policy
    $policy = $policies[$pickSecond]
    # toggle `pickSecond` for next time
    $pickSecond = -not $pickSecond

    $SpecificEndpoint.policyId = $policy
    # ... perform API call
}

PowerShell will automatically convert $false to 0 and $true to 1 and the $policy expression thus alternates between $policies[0] and $policies[1]

  •  Tags:  
  • Related