Stig Perez
Stig Perez

Reputation: 3833

How do I convert from object to string

I'm new to PowerShell so this will probably be easy to answer. Suppose I create an array like so:

$array1 = "a", "b", "c"

Then I create another array:

$array2 = $array1|select-object{$_}

What I would like to do is to join all the values in $array2 so I end up with the string "a b c", but using -join " " on $array2 just produces an empty result. Can someone explain to me how I can solve this?

Upvotes: 2

Views: 4015

Answers (3)

Joey
Joey

Reputation: 354774

An easy way to do what you need here in PowerShell is

"$array1"

or

'' + $array1

both of which will join the array elements with $OFS or space if $OFS is $null.

But as others have noted, your Select-Object call is wrong. Select-Object takes property names, not a scriptblock. Maybe you wanted ForEach-Object in that case?

Upvotes: 1

Akim
Akim

Reputation: 8679

Just replace $array2 = $array1|select-object{$_} with $array2 = $array1 | select-object or $array2 = $array1

$array1 = "a", "b", "c"

#expected output: a b c
$array1 -join " "

#here it is
$array2 = $array1 | select-object

#expected output: a b c
$array2 -join " "

#here it is
$array2 = $array1

#expected output: a b c
$array2 -join " "

Upvotes: 2

CB.
CB.

Reputation: 60958

Modify

$array2 = $array1|select-object{$_}

in

$array2 = $array1

then

$array2 -join ' '

works!

Upvotes: 0

Related Questions