如何将数组对象转换为PowerShell中的字符串?
如何将数组对象转换为字符串?如何将数组对象转换为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
对于未启动(像我一样)'$ ofs'被记录[在这里](http:// *。com/documentation/powershell/5353 /自动变量/ 19045/ofs) – Liam
*文档已关闭,因此Liam的链接已死亡。下面是对输出字段分隔符$ OFS的另一种解释:https://blogs.msdn.microsoft.com/powershell/2006/07/15/psmdtagfaq-what-is-ofs/ –
你可以像这样指定类型:
[string[]] $a = "This", "Is", "a", "cat"
检查类型:
$a.GetType()
确认:
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String[] System.Array
1.4.3 $一个:
PS C:\> $a This Is a cat
我发现将数组管道到out-string
cmdlet的效果也很好。
例如:
PS C:\> $a | out-string
This
Is
a
cat
这取决于你的最终目标,以哪种方法是最好的使用。
仅供参考:只要执行'$ a'与$ a |有相同的效果out-string' – JohnLBevan
@JohnLBevan并不总是如此。 '($ a | out-string).getType()'= String。 '$ a.getType()'= Object []。如果您使用$ a作为期望字符串的方法的参数(例如'invoke-expression'),那么'$ a | out-string'具有明显的优势。 – rojo
从管
# 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'
1> $a = "This", "Is", "a", "cat"
2> [system.String]::Join(" ", $a)
两名执行操作,并输出到主机,但不修改$一个:
3> $a = [system.String]::Join(" ", $a)
4> $a
这是一只猫
5> $a.Count
1
$a = "This", "Is", "a", "cat"
foreach ($word in $a) { $sent = "$sent $word" }
$sent = $sent.Substring(1)
Write-Host $sent
见我的答案,但你的代码的工作就好了。你为什么说“没有运气”? –
对不起,是的,它似乎工作,我想我测试了这件事后,我搞砸了。 – jrara