如何在PowerShell中将定界字符串转换为嵌套哈希表? [英] How can I turn a delimited string into a nested hashtable in PowerShell?
问题描述
我正在努力寻找一种巧妙的方法来将定界的字符串转换为哈希表.例如,给定字符串:
I am struggling to find a neat way to turn a delimited string into a hashtable. For example given the string:
UK_Kent_Margate
我想将其转换为如下所示的PowerShell HashTable:
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?
推荐答案
也许是这样的事情?
$string = 'UK_Kent_Margate'
$result = @{}
$Parts = $string.split('_')
0..($parts.count -1) |
foreach {
iex "`$result.$($parts[0..$_] -join '.') = @{}"
}
为了帮助您理解它的工作原理,只需删除iex(invoke-expression),然后让其输出正在创建的字符串即可执行:
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 = @{}
这篇关于如何在PowerShell中将定界字符串转换为嵌套哈希表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!