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

PowershellPowershell 2.0

Powershell Problem Overview


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?

Powershell Solutions


Solution 1 - Powershell

$a = 'This', 'Is', 'a', 'cat'

Using double quotes (and optionally use the separator $ofs)

# This Is a cat
"$a"

# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"

Using operator join

# This-Is-a-cat
$a -join '-'

# ThisIsacat
-join $a

Using conversion to [string]

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-'
[string]$a

Solution 2 - Powershell

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.

Solution 3 - Powershell

1> $a = "This", "Is", "a", "cat"

2> [system.String]::Join(" ", $a)

Line two performs the operation and outputs to host, but does not modify $a:

3> $a = [system.String]::Join(" ", $a)

4> $a

This Is a cat

5> $a.Count

1

Solution 4 - Powershell

From a pipe

# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}

# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}

Write-Host

# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'

# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'

Example

Solution 5 - Powershell

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

Solution 6 - Powershell

$a = "This", "Is", "a", "cat"

foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)

Write-Host $sent

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjraraView Question on Stackoverflow
Solution 1 - PowershellRoman KuzminView Answer on Stackoverflow
Solution 2 - PowershellJeremy SaundersView Answer on Stackoverflow
Solution 3 - PowershellTCCView Answer on Stackoverflow
Solution 4 - PowershellZomboView Answer on Stackoverflow
Solution 5 - PowershellAmeer DeenView Answer on Stackoverflow
Solution 6 - PowershellUnderverseView Answer on Stackoverflow