如何将数组对象转换为字符串?
我试着:
$a = "This", "Is", "a", "cat"
[system.String]::Join(" ", $a)
运气不好。PowerShell中有哪些不同的可能性?
如何将数组对象转换为字符串?
我试着:
$a = "This", "Is", "a", "cat"
[system.String]::Join(" ", $a)
运气不好。PowerShell中有哪些不同的可能性?
当前回答
$a = "This", "Is", "a", "cat"
foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)
Write-Host $sent
其他回答
我发现将数组管道到Out-String cmdlet也能很好地工作。
例如:
PS C:\> $a | out-string
This
Is
a
cat
这取决于你的最终目标,哪种方法是最好的。
1> $a = "This", "Is", "a", "cat"
2> [system.String]::Join(" ", $a)
第二行执行操作并输出到host,但不修改$a:
3> $a = [system.String]::Join(" ", $a)
4> $a
This Is a cat
5> $a.Count
1
你可以这样指定类型:
[string[]] $a = "This", "Is", "a", "cat"
检查类型:
$a.GetType()
确认:
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String[] System.Array
输出:美元
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
从管子里
# 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'
例子