0

I have a json file, test.json, like the below

[
{ "STORE":"2001", "UUID":"d7985d5f", "Clock1":"91", "Type":"IP" },
{ "STORE":"2002", "UUID":"821a0368", "Clock1":"92", "Type":"GT" }
]

And I am getting a comma-separated string as below

$StoreInput = "2001,2002"
$StoreArray = $StoreInput.Split(",")

$storemap = "location\test.json" | ConvertFrom-Json

What I want to do is, read $StoreArray, check the Type of each store against $storemap, and run function according to the type, passing uuid and Clock1

if (type = IP) {
    Function1 -Clock $Clock1 (from the json) -UUID $UUID (from the json) #Value of 2001's
}
elseif (type = GT) {
    Function2 -Clock $Clock1 (from the json) -UUID $UUID (from the json) #Value of 2002's
}

How do I go about doing this?

Laba Ningombam
  • 105
  • 1
  • 2
  • 7

1 Answers1

1

First you'll want to make sure you actually read the contents of the json file:

$StoreInput = "2001,2002"
$StoreArray = $StoreInput.Split(",")

$storemap = Get-Content "location\test.json" | ConvertFrom-Json

Since $storemap is actually an array, iterating over it is as easy as piping to the ForEach-Object command:

$storemap |ForEach-Object {
    # $_ will contain the current item/row from the array
}

To test for equality between two values, use the -eq operator - = is only for assignment in PowerShell:

$storemap |ForEach-Object {
  if($_.type -eq 'IP') {
    function1 -Clock $_.clock1 -UUID $_.UUID
  }
  elseif($_.type -eq 'GT') {
    function2 -Clock $_.clock1 -UUID $_.UUID
  }
}

Since we're passing the exact same arguments no matter what, we can extract those values and place them in a splatting table that we can then use for either function:

$storemap |ForEach-Object {
  # prepare the arguments to be passed to the function
  $paramArgs = @{
    Clock = $_.clock1
    UUID  = $_.UUID
  }

  # then decide which function to call...
  if($_.type -eq 'IP') {
    function1 @paramArgs
  }
  elseif($_.type -eq 'GT') {
    function2 @paramArgs
  }
}

If you want to filter the array so you only get stores with one of the IDs stored in $storeArray, use Where-Object:

$storemap |Where-Object STORE -in $storeArray |ForEach-Object { ... }
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Thank you so much @Mathias R. Jessen Here, I want to iterate each store in $StoreArray and check it against $storemap. Is there any other way then running two For Loop for the same? – Laba Ningombam Jul 19 '23 at 10:20
  • @LabaNingombam I've added a snippet showing how you can filter `$storemap` based on the values in `$storeArray` :) – Mathias R. Jessen Jul 19 '23 at 10:23