2

I have non-working code similar to the following:

$list = Get-VM | format-table VMElementName -HideTableHeaders | out-string
$array=@($list)

Write-Host $array[1]

What I end up is $array[0] filled with a list of data and no values in $array[1] or higher.

String1
String2
String3

What is the best way to parse this list to populate the array?

2
  • 2
    Rather than format-table, you should use select-object. That way you are still working with objects rather than strings. If you don't want the header, you can use the -ExpandProperty parameter. Commented Dec 11, 2013 at 19:33
  • 1
    To expand on @Entbark's comment, don't ever use Format-Table (or any other Format- cmdlet) unless you never want to use that data as data again. As soon as you format it, it's no longer usable. Also, you shouldn't use Write-Host in 90% of situations. Commented Dec 11, 2013 at 20:03

2 Answers 2

2

The easiest way to get that is just select out the property you want with Select -ExpandProperty:

$array = Get-VM | select -ExpandProperty VMElementName 

If you're running V3 or better, you can shorten that to:

$array = (Get-VM).VMElementName 
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome! If that answers your question, please mark it as answered, so it doesn't remain forever as an "Unanswered Question".
1

You don't need extra transformation logic. Just do the following

$array = ( Get-VM | format-table VMElementName -HideTableHeaders )

Write-Host $array[0]

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.