0

I have a PSCustomObject with properties and values. 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.

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 seems to get me close to what I want, but it does not appear to return an array

2
  • What code have you tried or searches did you do on SO for your problem? SO users are not in the habit of writing code without any effort made by the requester. Please edit your question to fit the MRE expected and we will assit where we can. Commented Dec 18, 2019 at 22:56
  • I added something close to the results I want, now. I understand that you want to see that I did research before asking, but I didn't think it was productive to list a bunch of dead end results. Commented Dec 19, 2019 at 20:46

3 Answers 3

2

Without using a loop you could do this:

$valArray = ($object.PSObject.Properties).Value

to give you an array of values

ValA
ValB
ValC
Sign up to request clarification or add additional context in comments.

Comments

0

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. 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. I used get-member on the object to get the NoteProperties, and then I'm splitting the definition object on the equal symbol.

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 ? {$._} 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.

Comments

0

Another Oneliner:

$variable = $object[0..$object.Count]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.