How can I turn a delimited string into a nested hashtable in PowerShell?

北城余情 提交于 2019-12-10 18:36:52

问题


I am struggling to find a neat way to turn a delimited string into a hashtable. For example given the string:

UK_Kent_Margate

I want to turn this into a PowerShell HashTable that looks like this:

$result = @{
    UK = @{
        Kent = @{
            Margate = @{}
        }
    }
 }

So I can easily break the string into an array using a split on the '_' character but then I am struggling (read stuck!) with testing and declaring each of the nested hashes in the results hash. I think I will need a recursive function which is no problem, but I cannot get my head around on how to test the right level in the results hash.

As the application I am writing could have an arbitrary number of '_' and thus nests I need to come up with a slick way of doing this, and I cannot think of how to do it.

Has anyone come across anything like this before and have any recommendations?


回答1:


Something like this, maybe?

$string = 'UK_Kent_Margate'

$result = @{}

$Parts = $string.split('_') 
0..($parts.count -1) |
foreach {
          iex "`$result.$($parts[0..$_] -join '.') = @{}"
        }

To help understand you it works, just remove the iex (invoke-expression), and let it output the strings it's creating to execute:

$string = 'UK_Kent_Margate'

$result = @{}

$Parts = $string.split('_') 
0..($parts.count -1) |
foreach {
          "`$result.$($parts[0..$_] -join '.') = @{}"
        }

$result.UK = @{}
$result.UK.Kent = @{}
$result.UK.Kent.Margate = @{}



回答2:


Rather than recursive you need to thing about doing things in reverse. Split to an array then reverse the array before building up the nested hashtables:

$s = "UK_Kent_Margate"
$t = $s -split '_'
[array]::Reverse($t)
[hashtable]$result = @{}
foreach ($w in $t) { $result = @{ $w = $result } }
$result

Name                           Value                                           
----                           -----                                           
UK                             {Kent}                                          

$result.UK.Kent

Name                           Value                                           
----                           -----                                           
Margate                        {} 



回答3:


An old school solution:

$input = @("UK_Kent_Margate");

$result = @{};
$input | foreach {
  $keys = $_ -split "_";
  $hs = $result;
  $keys | foreach {
    $hs[$_] = @{};
    $hs = $hs[$_];  
  }
}


来源:https://stackoverflow.com/questions/21047772/how-can-i-turn-a-delimited-string-into-a-nested-hashtable-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!