0

My JSON contains this part with multiple values in EnvironmentIds variable:

Name: Test
EnvironmentIds : {Environments-102, Environments-103}

If I would have simple variable $ENV with single value I would know how to check if that value exists in that list.

$ENVIRONMENT="Environments-103"

$json | ForEach-Object {
if ($_.EnvironmentIds -contains "$ENVIRONMENT") {
                              Write-Host($_.Name,$ENVIRONMENT)
                              }

But what should I do, if $ENVIRONMENT is not a single value but a list:

$ENVIRONMENT =  @ ("Environments-103", "Environments-104")

How to check if element from this list belongs - it is contained within the EnvironmentIds json list? I want to print that specific value from the list which is contained in the JSON values.

1 Answer 1

2

But what should I do, if $ENVIRONMENT is not a single value but a list:

Where-Object would be a natural fit for this

$data = @{
    Name =  "Test"
    EnvironmentIds = "Environments-102", "Environments-103"
}

$ENVIRONMENT = "Environments-103", "Environments-104"

$matches = $ENVIRONMENT | Where-Object { $data.EnvironmentIds -eq $_ }

Write-Host $matches

Note that -eq works on arrays (1,2,3,4,5 -eq 4 results in 4). The above prints:

Environments-103

If there is more than one match, it will print more than one result.

Of course you can turn it around, same thing:

$matches = $data.EnvironmentIds | Where-Object { $ENVIRONMENT -eq $_ }
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Tomalak, thanks for the assistance but you change my current object $._ on which I am iterating. I did not want that. As you see I am already printing the Name from my current object on which I am iterating with $._ Write-Host($_.Name...) - it is importnat for me to keep that current iteration. Iteration for the "ENVIRONEMENT" should be the second one, which is related to my current iteration , where in the same time I am extracting the name from current object.
@AndreyDonald data.EnvironmentIds | Where-Object { $ENVIRONMENT -eq $_ } | ForEach-Object { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.