Home > Back-end >  How to format the List output in specific format in powershell?
How to format the List output in specific format in powershell?

Time:01-13

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

RequiredFormat:

{id1},{id2}

Mycode:

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

MyOutput:

id1

id2

How to convert my output into required format? Can anyone please help me out regarding the same ?

CodePudding user response:

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)
    }
}

CodePudding user response:

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 ','
  • Related