假设我在 Powershell v3 中有一个哈希数组:
> $hashes = 1..5 | foreach { @{Name="Item $_"; Value=$_}}
我可以将单个哈希转换为
PSCustomObject
像这样:> $co = [PSCustomObject] $hashes[0]
> $co | ft -AutoSize
Value Name
----- ----
1 Item 1
> $co.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
到现在为止还挺好。当我尝试将整个哈希数组转换为
PSCustomObjects
时出现问题在管道中:> ($hashes | foreach { [PSCustomObject] $_})[0].getType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
如您所见,我得到了
Hashtable
的数组。对象,而不是 PSCustomObjects
.为什么我会得到不同的行为,我怎样才能完成我想要的?谢谢。
最佳答案
我还没有弄清楚确切的原因(每个人都在学习一些东西),但你的问题与 $_
相关。管道元素不知何故。如果我强制使用 $_
,我可以让你的代码工作。
$hashes = 1..5 | foreach { @{Name="Item $_"; Value=$_}}
$hashes | %{([pscustomobject][hashtable]$_)}
输出
Value Name
----- ----
1 Item 1
2 Item 2
3 Item 3
4 Item 4
5 Item 5
有点好奇
我不喜欢
Name
和 Value
, 在我测试的时候(这是一个字面哈希表的标题,我在测试时发现它令人困惑),所以我将后者更改为 Data
然后输出不同。我只是出于好奇才发布它。很难在帖子中显示结果。Name Data
---- ----
Item 1 1
Item 2 2
Item 3 3
Item 4 4
Item 5 5
关于powershell - 如何从 Powershell v3 中的哈希数组生成 PSCustomObjects 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29548180/