gpt4 book ai didi

powershell - 从函数/脚本返回 ArrayList

转载 作者:行者123 更新时间:2023-12-04 22:47:16 25 4
gpt4 key购买 nike

鉴于以下脚本:

function f {
[CmdletBinding()]Param()
Write-Verbose 'f: Start'
$t = New-Object 'System.Collections.ArrayList'
Write-Verbose $t.GetType().Name
return $t
}

$things = New-Object 'System.Collections.ArrayList'
$things.GetType().Name
$things = f -verbose
$things.GetType().Name

为什么不 $things Be-of-type ArrayList在最后一行?

最佳答案

输出集合(不仅仅是数组)会导致 PowerShell 默认枚举它们 - 即,集合的元素被一一发送到成功输出流。

  • 如果您通过在变量中捕获输出来收集这些元素,您总是会得到一个常规的 PowerShell 数组 ( [object[]] ),除非只有一个元素,它按原样捕获。

  • 为了防止这种情况 - 即, 将集合作为一个整体输出 - 用:
    Write-Output -NoEnumerate $t
    A 更短、更高效,但不太明显的替代方案 是将集合包装在辅助单元素数组中,一元形式为 , ,数组构造运算符,它使 PowerShell 枚举外部数组并按原样输出集合:
    , $t    # implicit output, no Write-Output needed

    关于powershell - 从函数/脚本返回 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50843357/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com