Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Hashtable to a string of key value pairs

Tags:

powershell

I have a hashtable of file extensions with counts

like 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 looking for a more elegant way (removing trailing ; is optional)

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

Thoughts???

like image 781
Jason Horner Avatar asked Sep 24 '14 03:09

Jason Horner


1 Answers

PowerShell won't automatically enumerate a hashtable, so you're forced to call GetEnumerator() or the Keys property. After that, there are a few options. First, using $OFS Ouptut Field Seperator. This string is used when an array is converted to a string. By default, this 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 ';'
like image 190
Jason Shirk Avatar answered Sep 20 '22 17:09

Jason Shirk