Powershell 中的 PsObject 数组 [英] PsObject array in powershell
本文介绍了Powershell 中的 PsObject 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
$a = @()
for ($i = 0; $i -lt 5; $i++)
{
$item = New-Object PSObject
$item | Add-Member -type NoteProperty -Name 'Col1' -Value 'data1'
$item | Add-Member -type NoteProperty -Name 'Col2' -Value 'data2'
$item | Add-Member -type NoteProperty -Name 'Col3' -Value 'data3'
$item | Add-Member -type NoteProperty -Name 'Col4' -Value 'data4'
$a += $item
}
使用此代码,我可以得到如下结果:
With this code I'm able to have a result like this:
Col1 Col2 Col3 Col4
---- ---- ---- ----
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
嗯,这很好,但如何更简单、更恰当地实现它呢?有没有办法创建 Array PsObject
也许?
Well, it's good, but how to achieve it more simply and more proper? Is there a way to create Array PsObject
maybe?
我正在使用 Powershell v4
.
推荐答案
我喜欢将 PSCustomObject
转换为 hashtable
:
I like the PSCustomObject
cast to a hashtable
:
$a = for ($i = 0; $i -lt 5; $i++){
[PSCustomObject] @{
Col1 = 'data1'
Col2 = 'data2'
Col3 = 'data3'
Col4 = 'data4'
}
}
您可以将 for
循环分配给 $a
You can just assign the for
loop to $a
或者单线:
$a = 1 .. 5 | % { [PSCustomObject] @{Col1 = 'data1'; Col2 = 'data2';Col3 = 'data3';Col4 = 'data4';}}
这篇关于Powershell 中的 PsObject 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文