1

Im starting to learn PowerShell and have been trying to create a foreach loop so that if one of the JSON items has a status other than STARTED, it runs a command using its name as a variable in the executable command. Here is what my json txt file looks like;

{
  "UNIT": {
    "name": "AB",
    "address": "fadasdaer",
    "status": "MIA"
  },
  "UNIT": {
    "name": "CD",
    "address": "fadasdahsfaaer",
    "status": "STARTED"
  },
    "UNIT": {
    "name": "EF",
    "address": "9afahegt",
    "status": "DEAD"
  }
}

And what I am trying to do is read this from my json.txt and get it to run a foreach loop and execute a command where the name is incorporated in the command. I currently have something like this, but my PowerShell understand is limited and it doesnt work...

$JSON = json.txt
$check = $JSON | ConvertFrom-Json
$started=STARTED

foreach($unit in $check.unit){
    if ($unit.status -notmatch $started) {
    $name=$unit.name
    executable.exe start $name
    }

}

Any guidance would be greatly appreciated.

2
  • 2
    $started=STARTED -> $started = 'STARTED' Commented Jul 16, 2018 at 22:05
  • 3
    Your JSON is malformed. You can't have duplicate keys. Commented Jul 16, 2018 at 22:34

1 Answer 1

7

Your primary problem is that your JSON is malformed: it defines a single object and then defines its UNIT property multiple times.

You should define it as an array: note the enclosing top-level [...] and the absence of UNIT properties:

[
  {
    "name": "AB",
    "address": "fadasdaer",
    "status": "MIA"
  },
  {
    "name": "CD",
    "address": "fadasdahsfaaer",
    "status": "STARTED"
  },
  {
    "name": "EF",
    "address": "9afahegt",
    "status": "DEAD"
  }
]

With both the JSON input and your other syntax problems corrected:

$JSON = 'json.txt'
$check = Get-Content -Raw $JSON | ConvertFrom-Json
$started = 'STARTED'

foreach ($unit in $check) {
  if ($unit.status -notmatch $started) {
    $name = $unit.name
    executable.exe start $name
  } 
}

If you cannot fix the JSON at the source, you can transform it yourself before passing it to ConvertFrom-Json:

$check = (Get-Content -Raw $JSON) `
  -replace '\A\{', '[' `
  -replace '\}\Z', ']' `
  -replace '"UNIT": ' | ConvertFrom-JSON
Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately, my json is always giving me the UNIT at the start... it can never be changed... is there are a way to integrate through each row of the JSON file? Possibly change each key in the file?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.