[英]PowerShell: How do I convert an array object to a string in PowerShell?
如何將數組對象轉換為字符串?
我試過:
$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"
使用運算符連接
# This-Is-a-cat
$a -join '-'
# ThisIsacat
-join $a
使用轉換為[string]
# This Is a cat
[string]$a
# This-Is-a-cat
$ofs = '-'
[string]$a
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
從管道
# 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'
您可以像這樣指定類型:
[string[]] $a = "This", "Is", "a", "cat"
檢查類型:
$a.GetType()
確認:
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String[] System.Array
輸出 $a:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.