Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So I'm tweaking some Powershell libraries and I've a simple question that I'd like to solve in the best way.....

In short, I've some custom PSObjects in an array:

$m1 = New-Object PSObject –Property @{Option="1"; Title="m1"}
$m2 = New-Object PSObject –Property @{Option="2"; Title="m2"}
$m3 = New-Object PSObject –Property @{Option="3"; Title="m3"}

$ms = $m1,$m2,$m3

that I wish to convert into a string array.... ideally a single string array which has an entry for each item with the properties concatenated. i.e.

"1m1", "2m2", "3m3"

I've tried $topMenu | Select-Object Option,Title and $topMenu | %{ "O: $_.Option T: $_.Title "} but they give me arrays of the PSObject (again) or arrays of arrays.

share|improve this question

1 Answer

up vote 2 down vote accepted

This will give you what you want:

$strArray = $ms | Foreach {"$($_.Option)$($_.Title)"}

Select-Object is kind of like a SQL Select it projects the selected properties onto a new object (pscustomobject in v1/v2 and Selected. in V3). You second approach doesn't work because $_.Option in a string will only "interpolate" the variable $_. It won't evaluate the expression $_.Option. You can get double-quoted strings to evaluate expressions by using subexpressions e.g. "$(...)" or "$($_.Option)".

share|improve this answer
KEITH! Wow I hoped you'd be watching the powershell tags... any chance of a 'why' ? I is it to invoke again??? – penderi Jan 15 at 16:20
Superb Keith. Thanks a lot. – penderi Jan 15 at 16:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.