如何将参数中的一些数据传递给 Hashtable 数组?
filnemane.ps1 -param @{ a = 1, b = 2, c =3}, @{ a = 4, b = 5, c =6}
到这个输出:
$param = @(
@{
a=1,
b=2,
c=3
},
@{
a=4,
b=5,
c=6
}
)
谢谢。
最佳答案
您将参数声明为 [hashtable[]]
类型(即 [hashtable]
的数组):
# filename.ps1
param(
[hashtable[]]$Hashtables
)
Write-Host "Hashtables: @("
foreach($hashtable in $Hashtables){
Write-Host " @{"
foreach($entry in $hashtable.GetEnumerator()){
Write-Host " " $entry.Key = $entry.Value
}
Write-Host " }"
}
Write-Host ")"
有了你的样本输入,你会得到类似的东西:
PS C:\> .\filename.ps1 -Hashtables @{ a = 1; b = 2; c =3},@{ a = 4; b = 5; c =6}
Hashtables: @(
@{
c = 3
b = 2
a = 1
}
@{
c = 6
b = 5
a = 4
}
)
请注意,输出不一定会保留输入中的键顺序,因为这不是哈希表的工作方式:)
如Matthew helpfully points out ,如果维护键顺序很重要,请改用有序字典(
[ordered]@{}
)。要支持接受任何一种而不弄乱键顺序,请将参数类型声明为
[System.Collections.IDictionary]
的数组。 - 两种类型都实现的接口(interface):param(
[System.Collections.IDictionary[]]$Hashtables
)
关于哈希表的 Powershell 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60287601/