Convert a hashtable to a string of key value pairs

I have a hash table of file extensions with count

So:

$FileExtensions = @{".foo"=4;".bar"=5} Function HashConvertTo-String($ht) { foreach($pair in $ht.GetEnumerator()) { $output+=$pair.key + "=" + $pair.Value + ";" } $output } $hashString = HashConvertTo-String($FileExtensions) $hashString.TrimEnd(';') -eq ".foo=4;.bar=5" 

The last line should return $ true

This works, but is looking for a more elegant way (removing trailing, optional)

I guess what I'm really looking for is a -join for hashtables or something like that

Thoughts ???

+6
source share
2 answers

PowerShell will not automatically list the hash table, so you have to call the GetEnumerator() or Keys property. After that there are several options. First use the $OFS Ouptut Field Seperator. This string is used when the array is converted to a string. The default is "" , but you can change it:

 $FileExtensions = @{".foo"=4;".bar"=5} $OFS =';' [string]($FileExtensions.GetEnumerator() | % { "$($_.Key)=$($_.Value)" }) 

Next, using the -join operator:

 $FileExtensions = @{".foo"=4;".bar"=5} ($FileExtensions.GetEnumerator() | % { "$($_.Key)=$($_.Value)" }) -join ';' 
+18
source

Not tested, but this code should work:

 Function HashConvertTo-String($ht) { $first = $true foreach($pair in $ht.GetEnumerator()) { if ($first) { $first = $false } else { $output += ';' } $output+="{0}={1}" -f $($pair.key),$($pair.Value) } $output } 
0
source

Source: https://habr.com/ru/post/975747/


All Articles