繁体   English   中英

PowerShell:如何在 PowerShell 中将数组对象转换为字符串?

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

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

我试过:

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

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

$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"

使用运算符连接

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

# ThisIsacat
-join $a

使用转换为[string]

# This Is a cat
[string]$a

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

我发现将数组通过管道传输到Out-String cmdlet 也很有效。

例如:

PS C:\> $a  | out-string

This
Is
a
cat

哪种方法最适合使用取决于您的最终目标。

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

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

第二行执行操作并输出到主机,但不修改 $a:

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

4> $a

This Is a cat

5> $a.Count

1

从管道

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

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

写主机

# 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

输出 $a:

PS C:\> $a 
This 
Is 
a 
cat
$a = "This", "Is", "a", "cat"

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

Write-Host $sent

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM