一个完整的例子:
# Create a sample ArrayList, as returned by
$err = [System.Collections.ArrayList] ('one', 'two')
# Construct a custom object ([pscustomobject]) with an .ErrorMessage
# property that contains the array list
$obj = [pscustomobject] @{ ErrorMessage = $err }
# !! Write-Host results in UNHELPFUL display:
# !! Note how instead of listing the *elements* of the ArrayList
# !! the *type name* ("System.Collections.ArrayList") is printed instead.
PS> Write-Host $obj
@{ErrorMessage=System.Collections.ArrayList}
# OK: Out-Host produces richly formatted *display-only* output.
PS> $obj | Out-Host
ErrorMessage
------------
{one, two}
# OK as well: *implicit* output, *as data* - same representation.
PS> $obj
ErrorMessage
------------
{one, two}
注意:对于 direct 显示元素不是复杂对象的集合的输出,Write-Host 在 single-行输出是需要的,因为元素然后只是空间连接:
$err = [System.Collections.ArrayList] ('one', 'two')
# OK with collection of non-complex objects to get a
# *single-line* representation.
# Out-Host and implicit output print each element on its own line.
PS> Write-Host $err
one two
您甚至可以使用-Separator 来使用空格以外的分隔符:
PS> Write-Host -Separator / 'one', 'two'
one/two
当然,您也可以使用 表达式 来创建这样的字符串,使用 -join、string joining operator 运算符,这将允许您将输出 用作数据:
PS> 'one', 'two' -join '/'
one/two
可选阅读:为什么传递给-ErrorVariable 的目标变量会收到System.Collections.ArrayList 实例:
common -ErrorVariable parameter——实际上是所有常见的-*Variable 参数,它们在变量中收集流的输出——总是返回一个带有收集输出的 System.Collections.ArrayList 实例,这在两个方面令人惊讶:
-
PowerShell 通常使用[object[]]arrays 作为其默认的集合数据类型。
-
另外,在-OutVariable的情况下,行为与管道的direct输出不一致,其中一个命令输出的单个对象是输出as such - 而不是被包装在一个集合中,例如 ArrayList 在这种情况下;也就是说,即使您希望以下两个命令是等价的,它们也不是:
$out = Get-Date
# -> $out is a [datetime] instance.
# !! -OutVariable *always* creates ArrayList.
$null = Get-Date -OutVariable out
# -> $out is a *single-element ArrayList* containing a [datetime] instance.
有关这些不一致的讨论,请参阅GitHub issue #3154。