如何将数组对象转换为PowerShell中的string?
如何将数组对象转换为string?
我试过了:
$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" 
使用运算符join
 # This-Is-a-cat $a -join '-' # ThisIsacat -join $a 
 使用转换为[string] 
 # This Is a cat [string]$a # This-Is-a-cat $ofs = '-' [string]$a 
 我发现将数组pipe道到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 
这是一只猫
 5> $a.Count 1 
从pipe道
 # 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' 
例
你可以像这样指定types:
 [string[]] $a = "This", "Is", "a", "cat" 
检查types:
 $a.GetType() 
确认:
     IsPublic IsSerial名称BaseType
     -------- -------- ---- --------
     True True String [] System.Array
输出$ a:
PS C:\> $ a 这个 是 一个 猫
 $a = "This", "Is", "a", "cat" foreach ( $word in $a ) { $sent = "$sent $word" } $sent = $sent.Substring(1) Write-Host $sent