0

I have a piece of code presented below, it takes values from a json file. This is a array of string --> $Json.Names. I would like to avoid duplicate lines like --> $Json.Names[0].Name {$Json.Names[0].Name; break}. Second case is that Array $Json.Names could have different length, array can have 6 and more or less elements. I want to make this switch statement more elastic. I tried to use for loop and while loop, but in this case these loops doesn't help me. Is there any clever method to make this code more sophisticated/elastic and avoid duplicate mentioned code lines$Json.Names[0].Name {$Json.Names[0].Name; break}

$Json = Get-Content "$path" | out-string | ConvertFrom-Json
$Name = switch ($Member) {
    $Json.Names[0].Name  {$Json.Names[0].Name; break}
    $Json.Names[1].Name  {$Json.Names[1].Name; break}
    $Json.Names[2].Name  {$Json.Names[2].Name; break}
    $Json.Names[3].Name  {$Json.Names[3].Name; break}
    $Json.Names[4].Name  {$Json.Names[4].Name; break}
    $Json.Names[5].Name  {$Json.Names[5].Name; break}
    $Json.Names[6].Name  {$Json.Names[6].Name; break}
    default {"Unknown Name"}
}
2
  • $Json.Names.Name |Where {$_ -like $member} Commented Nov 6, 2019 at 10:54
  • What does the json look like? Switch is a loop: switch (1..5) { $_ { $_ } } Commented Nov 6, 2019 at 13:08

2 Answers 2

2

Assuming this structure:

$json = [pscustomobject]@{names = [pscustomobject]@{name ='joe'},
  [pscustomobject]@{name ='john'},
  [pscustomobject]@{name ='james'}}

Assuming $member is a single name, you can say

$name = $json.names.name -eq $member # an array of one

$name would be a null array if there's no match.

if (! $name) { $name = 'Unknown Name' }

Or, in the language of Powershell 7 preview 5:

$name ??= 'Unknown Name'

You also may want to make a hashtable of the names.

Sign up to request clarification or add additional context in comments.

Comments

1

You can take advantage of property enumeration and simplify your code pretty significantly:

# define our default
$Name = "Unknown Name"

# define the list of names 
$Json = Get-Content "$path" | ConvertFrom-Json
$Names = $Json.Names.Name

# update $Name if applicable
if($Names -contains $member){
    $Name = $member
}

1 Comment

Thx, it helps me, tested pipeline, and it works, similar solution to this proposed by @js2010

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.