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???
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 ';'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With