Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I convert an array object to string? I tried:

$a = "This", "Is", "a", "cat"
[system.String]::Join(" ", $a)

with no luck. What are different possibilities in PowerShell?

share|improve this question
1  
See my answer but your code works just fine, too. Why do you say "with no luck"? –  Roman Kuzmin Oct 11 '11 at 9:30
    
Sorry, yes, it does seem to work, I think I messed up something when I tested this. –  jrara Oct 11 '11 at 9:41

3 Answers 3

up vote 62 down vote accepted
$a = "This", "Is", "a", "cat"

# This Is a cat
"$a"

Operator join

# This Is a cat
$a -join ' '

# ThisIsacat
-join $a

Using conversion to [string] (and optionally use the separator $ofs)

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-' # ! after that all casts work in this way until $ofs changes !
[string]$a
share|improve this answer
1  
you are my hero!!! -join all by its self is pure magic!! –  mr.buttons Sep 19 '13 at 0:26

I know it's an old thread, but I found that piping the array to the out-string cmdlet works well too.

For example:

PS C:\> $a  | out-string

This
Is
a
cat

It depends on your end goal as to which method is the best to use.

share|improve this answer

You could specify type like this:

[string[]] $a = "This", "Is", "a", "cat"

Checking the type:

$a.GetType()

Confirms:

    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     String[]                                 System.Array

Outputting $a:

PS C:\> $a 
This 
Is 
a 
cat
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.