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.
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.
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.
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.
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.
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)".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With