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

jra*_*ara 159 powershell powershell-2.0

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

我试过了:

$a = "This", "Is", "a", "cat"
[system.String]::Join(" ", $a)
Run Code Online (Sandbox Code Playgroud)

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

Rom*_*min 271

$a = 'This', 'Is', 'a', 'cat'
Run Code Online (Sandbox Code Playgroud)

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

# This Is a cat
"$a"

# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"
Run Code Online (Sandbox Code Playgroud)

使用运算符连接

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

# ThisIsacat
-join $a
Run Code Online (Sandbox Code Playgroud)

使用转换为 [string]

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-'
[string]$a
Run Code Online (Sandbox Code Playgroud)

  • Stackoverflow文档已被关闭,因此Liam的链接已经死亡.这是$ OFS的另一个解释,输出字段分隔符:https://blogs.msdn.microsoft.com/powershell/2006/07/15/psmdtagfaq-what-is-ofs/ (11认同)
  • 对于未启动的(像我一样)`$ ofs`被记录在案[这里](http://stackoverflow.com/documentation/powershell/5353/automatic-variables/19045/ofs) (9认同)

小智 31

我发现将数组管道连接到Out-Stringcmdlet也很有效.

例如:

PS C:\> $a  | out-string

This
Is
a
cat
Run Code Online (Sandbox Code Playgroud)

这取决于您最终使用哪种方法的最终目标.

  • @JohnLBevan不总是.`($ a | out-string).getType()`= String.`$ a.getType()`= Object [].如果你使用$ a作为期望字符串的方法的参数(例如`invoke-expression`),那么`$ a | out-string`有明显的优势. (7认同)
  • 仅供参考:只需要`$ a`就可以和`$ a |一样 出string` (4认同)

小智 17

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

2> [system.String]::Join(" ", $a)
Run Code Online (Sandbox Code Playgroud)

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

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

4> $a
Run Code Online (Sandbox Code Playgroud)

这是一只猫

5> $a.Count

1
Run Code Online (Sandbox Code Playgroud)


小智 10

从管道

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

# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}
Run Code Online (Sandbox Code Playgroud)

写主机

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

# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'
Run Code Online (Sandbox Code Playgroud)

  • 这是一个了不起的技巧。这个例子不再起作用了,尽管这个答案已经有 5 年历史了,我还是尝试解释一下我今天学到的东西。`$ofs` 是 `Output Field Separator` 变量,当数组转换为字符串输出时使用。这里它是在脚本块中设置的,返回输入的字符串值(来自管道的数组),该值由命令“&”执行。我之前不知道 `$ofs` 以及接受脚本块作为参数的 `&` (2认同)