Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Custom Object arrays to String arrays in Powershell

Tags:

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.

like image 727
penderi Avatar asked Jan 15 '13 15:01

penderi


People also ask

How do I convert an array to a string in PowerShell?

Use " " to Convert an Array Object to String in PowerShell Copy $address = "Where", "are", "you", "from?" You can check the data type using the GetType() method. When you encode the array variable with " " , it will be converted into a string.

How do I convert an object to a string in PowerShell?

Description. The Out-String cmdlet converts input objects into strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the Stream parameter to direct Out-String to return one line at a time or create an array of strings.

How do you turn an array of objects into a string?

To convert a JavaScript array into a string, you can use the built-in Array method called toString . Keep in mind that the toString method can't be used on an array of objects because it will return [object Object] instead of the actual values.

How do I convert an array in PowerShell?

Now, for example, we want to convert the string into the array of the word. As you can see, we store the input string in $Inputstring variable, convert the string into the character array by using. TocharArray() function and store it in $CharArray variable and print each character within the array.


1 Answers

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

like image 135
Keith Hill Avatar answered Oct 29 '22 00:10

Keith Hill