penderi
penderi

Reputation: 9073

Converting Custom Object arrays to String arrays in Powershell

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.

Upvotes: 33

Views: 85592

Answers (2)

SherlockSpreadsheets
SherlockSpreadsheets

Reputation: 2360

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 

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201662

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)".

Upvotes: 60

Related Questions