Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 将哈希表转换为键值对字符串_Powershell - Fatal编程技术网

Powershell 将哈希表转换为键值对字符串

Powershell 将哈希表转换为键值对字符串,powershell,Powershell,我有一个带有计数的文件扩展名哈希表 像这样: $FileExtensions = @{".foo"=4;".bar"=5} Function HashConvertTo-String($ht) { foreach($pair in $ht.GetEnumerator()) { $output+=$pair.key + "=" + $pair.Value + ";" } $output } $hashString = HashConvertTo-String($FileExtens

我有一个带有计数的文件扩展名哈希表

像这样:

$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"
最后一行应返回$true

这是可行的,但要寻找一种更优雅的方式(删除尾随;是可选的)

我想我真正想要的是哈希表的连接或类似的东西


想法???

未经测试,但此代码应能正常工作:

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
  }

PowerShell不会自动枚举哈希表,因此您必须调用
GetEnumerator()
Keys
属性。在那之后,有几个选择。首先,使用
$OFS
输出字段分隔符。将数组转换为字符串时使用此字符串。默认情况下,这是
,但您可以更改它:

$FileExtensions = @{".foo"=4;".bar"=5}
$OFS =';'
[string]($FileExtensions.GetEnumerator() | % { "$($_.Key)=$($_.Value)" })
接下来使用-join操作符:

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