如何将数组对象转换为字符串?

我试着:

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

运气不好。PowerShell中有哪些不同的可能性?


当前回答

我发现将数组管道到Out-String cmdlet也能很好地工作。

例如:

PS C:\> $a  | out-string

This
Is
a
cat

这取决于你的最终目标,哪种方法是最好的。

其他回答

我发现将数组管道到Out-String cmdlet也能很好地工作。

例如:

PS C:\> $a  | out-string

This
Is
a
cat

这取决于你的最终目标,哪种方法是最好的。

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

使用双引号(可选使用分隔符$ofs)

# This Is a cat
"$a"

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

使用操作符join

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

# ThisIsacat
-join $a

使用转换到[string]

# This Is a cat
[string]$a

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

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

Write-Host $sent

从管子里

# 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'

例子

你可以这样指定类型:

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

检查类型:

$a.GetType()

确认:

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

输出:美元

PS C:\> $a 
This 
Is 
a 
cat