34

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 $ms | Select-Object Option,Title and $ms | %{ "O: $_.Option T: $_.Title "} but they give me arrays of the PSObject (again) or arrays of arrays.

2 Answers 2

61

This will give you what you want:

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

Select-Object is kind of like an SQL SELECT. It projects the selected properties onto a new object (pscustomobject in v1/v2 and Selected.<orignalTypeName> in V3). Your 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, for example, "$(...)" or "$($_.Option)".

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

2 Comments

KEITH! Wow I hoped you'd be watching the powershell tags... any chance of a 'why' ? I is it to invoke again???
I got a crazy multi-reply from a certain API that I couldn't properly parse until I found your solution. And it's 8 years old! But works like a charm. And who better to provide it than a PowerShell MVP 😎
0

I was also getting the same doesn't contain a method named 'op_Addition'. error message when trying to collect object values and add them to an array collection. It worked beautifully when wrapping the varaible with @( and ).

Here is a reference article:

PS script array collection

##USER PROFILES...
$UserProfiles= @("cg2208", "cg0769", "ms8659", "sw1650", "dc8141", "bc0397", "bm7261")
$UserProfiles
$aduserlist = @()
foreach ($user in $UserProfiles {
  $user 
  #Write-Host "Press any key to continue ..."
  #$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$aduser= Get-ADUser -Identity $user -Properties * | Select -Property  SamAccountName, Name, LastLogonDate, whenCreated, msExchWhenMailboxCreated, City, State, Department, Title, mailNickname, Description
#$aduserlist += $aduser | Select Name, SamAccountName, City, State, Department, Title, whenCreated, msExchWhenMailboxCreated, mailNickname, Description
#$aduserlist += $aduser | Foreach {"$($_.SamAccountName)$($_.Name)$($_.City)$($_.State)$($_.Title)$($_.whenCreated)$($_.msExchWhenMailboxCreated)$($_.mailNickname)$($_.Description)"}
$aduserlist += @($aduser)  
}
$aduserlist
$aduserlist | ft -auto 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.