1

I'm trying to create a list of Id's in specific format as shown below:

RequiredFormat:

{id1},{id2}

My code:

[System.Collections.Generic.List[System.String]]$IDList = @()
        foreach ($key in $keys) {
             $id =  $sampleHashTable[$key]
             $IDList.Add($id)   
        }
        echo  $IDList

My output:

id1

id2

How to convert my output into required format?

1
  • 1
    the possible way to have your desired output {id1},{id2} is as a String. Will no longer be a List or Array. Are you aware / ok with that? Commented Jan 12, 2023 at 15:17

2 Answers 2

2

To complement Mathias' helpful answer with a PowerShell (Core) 7+ alternative, using the Join-String cmdlet:

# Sample input values
[System.Collections.Generic.List[System.String]] $IDList = 'id1', 'id2'

# -> '{id1},{id2}'
$IDList | Join-String -FormatString '{{{0}}}' -Separator ','
  • -FormatString accepts a format string as accepted by the .NET String.Format method, as also used by PowerShell's -foperator, with placeholder {0} representing each input string; literal { characters must be escaped by doubling, which is why the enclosing { and } are represented as {{ and }}.

Alternatives that work in Windows PowerShell too:

Santiago Squarzon proposes this:

'{{{0}}}' -f ($IDList -join '},{')

Another - perhaps somewhat obscure - option is to use the regex-based -replace operator:

$IDList -replace '^', '{' -replace '$', '}' -join ','
Sign up to request clarification or add additional context in comments.

Comments

2

You can surround each list item in {} and then join them all together like this:

$IDList.ForEach({"{${_}}"}) -join ','

If you want to avoid empty strings in the list, remember to test whether the key actually exists in the hashtable before adding to the list:

foreach ($key in $keys) {
    if ($sampleHashTable.ContainsKey[$key]){
        $id = $sampleHashTable[$key]
        $IDList.Add($id)
    }
}

1 Comment

Hi Mathias .. Can you please look into this query ? stackoverflow.com/questions/75105771/…

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.