How do I convert an array object to a string in PowerShell?
如何将数组对象转换为字符串?
我试过:
| 1 2 | $a ="This","Is","a","cat" [system.String]::Join("", $a) | 
运气不好。PowerShell有哪些不同的可能性?
| 1 | $a = 'This', 'Is', 'a', 'cat' | 
使用双引号(也可以使用分隔符
| 1 2 3 4 5 6 | # This Is a cat "$a" # This-Is-a-cat $ofs = '-' # after this all casts work this way until $ofs changes! "$a" | 
使用运算符联接
| 1 2 3 4 5 | # This-Is-a-cat $a -join '-' # ThisIsacat -join $a | 
使用到
| 1 2 3 4 5 6 | # This Is a cat [string]$a # This-Is-a-cat $ofs = '-' [string]$a | 
我发现通过管道将数组连接到
例如:
| 1 2 3 4 5 6 | PS C:\> $a  | out-string This Is a cat | 
这取决于你的最终目标,哪种方法最适合使用。
| 1 2 3 | 1> $a ="This","Is","a","cat" 2> [system.String]::Join("", $a) | 
第二行执行操作并输出到主机,但不修改$A:
| 1 2 3 | 3> $a = [system.String]::Join("", $a) 4> $a | 
这是一只猫
| 1 2 3 | 5> $a.Count 1 | 
从管道
| 1 2 3 4 5 | # This Is a cat 'This', 'Is', 'a', 'cat' | & {"$input"} # This-Is-a-cat 'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"} | 
写入主机
| 1 2 3 4 5 | # This Is a cat Write-Host 'This', 'Is', 'a', 'cat' # This-Is-a-cat Write-Host -Separator '-' 'This', 'Is', 'a', 'cat' | 
例子
您可以这样指定类型:
| 1 | [string[]] $a ="This","Is","a","cat" | 
检查类型:
| 1 | $a.GetType() | 
确认:
| 1 2 3 |     IsPublic IsSerial Name                                     BaseType -------- -------- ---- -------- True True String[] System.Array | 
输出A:
| 1 2 3 4 5 | PS C:\> $a  This Is a cat | 
| 1 2 3 4 5 6 | $a ="This","Is","a","cat" foreach ( $word in $a ) { $sent ="$sent $word" } $sent = $sent.Substring(1) Write-Host $sent |