我该如何将数组对象转换为字符串?
我尝试了以下代码:
$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'
使用双引号(可选使用分隔符$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
$a
дёЋ$a | out-string
е…·жњ‰з›ёеђЊзљ„ж•€жћњгЂ‚ - JohnLBevan($a | out-string).getType()
的结果为字符串类型,而 $a.getType()
的结果为对象数组类型。如果你将 $a
作为期望接收字符串类型参数的方法(例如 invoke-expression
)的参数,那么 $a | out-string
显然更加优越。 - rojo1> $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'
$ofs
是 输出字段分隔符
变量,当将数组转换为输出字符串时使用。在这里,它被设置在脚本块中,返回输入(来自管道的数组)的字符串值,该值由命令 &
执行。我之前不知道 $ofs
,也不知道 &
接受脚本块作为参数。 - Martin Konopka$input
变量。https://learn.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.3#input - Winand
[string[]] $a = "This", "Is", "a", "cat"
检查数据类型:
$a.GetType()
确认结果:
是否公共 是否序列化 名称 基类 -------- -------- ---- -------- 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