Matt Leyland
Matt Leyland

Reputation: 2329

ForEach with Multiple Variables - Powershell

$Res is the Result of an

Invoke-RestMethod

I currently have the following code.

$ObjectGUIDS = $Res.ObjectGUID

$AccountID = $Res.ID

$I = 0

ForEach ($ObjectGUID in $ObjectGUIDS) {

    Write-Host $ObjectGUID ($AccountID[$I])


    $I = $I +1
}

The Output

81d651d5-aeab-4a6f-a102-3e420b5bb630 5
b0f0283a-187f-4fab-9b3d-de98491c8283 6
b84c830a-9c01-49d2-adbd-d70d80199de1 7

I want to loop through the results which is fine if I was only wanted the result from one variable ie - ObjectGUID or AccountID. The code above is a botch and I don't feel its remotely correct however it does seem to work.

I did try ForEach within a ForEach but this will return each $ObjectGUID 3 Times for Each $AccountID

$ObjectGUIDS = $Res.ObjectGUID

$AccountIDS = $Res.ID

ForEach ($ObjectGUID in $ObjectGUIDS) {
    ForEach ($AccountID in $AccountIDS) {

    Write-Host $ObjectGUID ($AccountID)

    }
}

The Output

81d651d5-aeab-4a6f-a102-3e420b5bb630 5
81d651d5-aeab-4a6f-a102-3e420b5bb630 6
81d651d5-aeab-4a6f-a102-3e420b5bb630 7
b0f0283a-187f-4fab-9b3d-de98491c8283 5
b0f0283a-187f-4fab-9b3d-de98491c8283 6
b0f0283a-187f-4fab-9b3d-de98491c8283 7
b84c830a-9c01-49d2-adbd-d70d80199de1 5
b84c830a-9c01-49d2-adbd-d70d80199de1 6
b84c830a-9c01-49d2-adbd-d70d80199de1 7

Upvotes: 1

Views: 2935

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23405

I think you might be over complicating things by bringing the two properties of $Res in to separate variables.

I think this would work instead:

ForEach ($Result in $Res) {
    Write-Host $Result.ObjectGUID $Result.ID
}

Upvotes: 2

Related Questions