PowerShell: How do I convert an array object to a string in 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
I found that piping the array to the Out-String
cmdlet works well too.
For example:
PS C:\> $a | out-stringThisIsacat
It depends on your end goal as to which method is the best to use.
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> $aThis Is a cat5> $a.Count1