[英]Get Values From Object as array in Powershell
I have a PSCustomObject with properties and values.我有一个带有属性和值的 PSCustomObject。 My goal is to quickly put the values in an array.
我的目标是快速将值放入数组中。 I am fairly new to powershell so I am unsure if this is something I can do in a single-line.
我对 powershell 相当陌生,所以我不确定这是否可以在单行中完成。
My object:我的对象:
object
propA : valA
propB : valB
propC : valC
I want to get an array of just the values as fast as possible, Ideally this would not involve a loop because this process will be done thousands of times.我想尽快获得一个仅包含值的数组,理想情况下这不会涉及循环,因为此过程将进行数千次。
valArray
valA, valB, valC
I have tried a couple things.我已经尝试了几件事。
$object | ft -HideTableHeaders
$object | ft -HideTableHeaders
seems to get me close to what I want, but it does not appear to return an array $object | ft -HideTableHeaders
似乎让我接近我想要的,但它似乎没有返回一个数组
Without using a loop you could do this:不使用循环,你可以这样做:
$valArray = ($object.PSObject.Properties).Value
to give you an array of values给你一个值数组
ValA ValB ValC
Here is my approach following your not using a loop guideline, even though I would use a loop otherwise.这是我遵循您不使用循环指南的方法,即使否则我会使用循环。
$object = [pscustomobject]@{
propA = 'ValA'
propB = 'ValB'
propC = 'ValC'
propD = 'ValD'
propE = 'ValE'
}
[array]$Array123 = (($object | get-member -MemberType NoteProperty).definition).split("=")
[array]$Array123 = [array]$Array123 -replace "^string.*$","" | ? {$_}
[array]$Array123
So I made a dummy object called $object.所以我制作了一个名为 $object 的虚拟对象。 Then I used type accelerator [array] on $Array123 so powershell is aware I'm looking to create an array with my command on the right of the "=" symbol.
然后我在 $Array123 上使用了类型加速器 [array],所以 powershell 知道我正在寻找使用“=”符号右侧的命令创建一个数组。 I used
get-member
on the object to get the NoteProperties, and then I'm splitting the definition object on the equal symbol.我在对象上使用
get-member
来获取 NoteProperties,然后我在等号上拆分定义对象。
This creates an array that looks like this.这将创建一个看起来像这样的数组。
string propA
ValA
string propB
ValB
string propC
ValC
string propD
ValD
string propE
ValE
Then I regex to remove the lines that begin with "string"... and lastly pipe to ? {$._}
然后我正则表达式删除以“string”开头的行......最后通过管道传输到
? {$._}
? {$._}
in order to remove the lines we emptied out with our regex. ? {$._}
以删除我们用正则表达式清空的行。
After our regex the array will look like so:在我们的正则表达式之后,数组将如下所示:
ValA
ValB
ValC
ValD
ValE
I am doubtful this is faster than a simple foreach loop, but it does fall under your no loop in the answers rule.我怀疑这比简单的 foreach 循环快,但它确实属于答案规则中的无循环。
另一个单线:
$variable = $object[0..$object.Count]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.