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


175

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

我试过了:

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

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


5
看到我的答案,但您的代码也很好。你为什么说“没有运气”?
罗曼·库兹敏

4
抱歉,是的,它确实起作用了,我想我在测试时弄乱了一些东西。
jrara 2011年

Answers:


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

9
对于未启动的(比如我)$ofs是记录在这里
利亚姆

13
Stackoverflow文档已关闭,因此Liam的链接已死。这里的$ OFS,输出域的另一种解释:blogs.msdn.microsoft.com/powershell/2006/07/15/...
西蒙Tewsi

为什么叫OFS?考虑到数十年来一直被称为标准外壳上的IFS,这是一个奇怪的名字。
JohanBoulé18年

1
@JohanBoulé:因为使用输入字段分隔符的第一个字符作为输出字段分隔符是一个讨厌的技巧-不允许使用多字符字符串分隔字段。(例如,awk具有FS和OFS变量)。
马丁·邦纳

@martin bonner:谢谢,现在有意义。我不知道我是怎么弄糟的。
JohanBoulé18年

36

我发现将数组管道传递到Out-Stringcmdlet的效果也很好。

例如:

PS C:\> $a  | out-string

This
Is
a
cat

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


4
仅供参考:这样做$a$a | out-string
JohnLBevan

7
@JohnLBevan并非总是如此。 ($a | out-string).getType()=字符串。 $a.getType()=对象[]。如果将$ a用作需要字符串的方法的参数(invoke-expression例如),则$a | out-string具有明显的优势。
rojo,2016年

18
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

10

从管道

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


这是惊人的把戏。该示例不再起作用,即使该答案已有5年历史了,我也要尝试解释一下我今天所学的内容。的$ofsOutput Field Separator当阵列被转换成输出的字符串所使用的变量。在这里,它在脚本块中设置,返回由命令执行的输入(来自管道的数组)的字符串值&。我以前不知道$ofs,也没有&接受脚本块作为参数
Martin Konopka,

3

您可以这样指定类型:

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

检查类型:

$a.GetType()

确认:

    IsPublic IsSerial名称BaseType
    -------- -------- ---- --------
    True True String [] System.Array

输出$ a:

PS C:\> $ a 
这个 
是 
一个 
猫

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

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

Write-Host $sent
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.