Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

powershell - Returning ArrayList from Function/Script

Given the following script:

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

Why wouldn't the $things be-of-type ArrayList at the final line?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Outputting collections (not just arrays) causes PowerShell to enumerate them by default - i.e., the collection's elements are sent one by one to the success output stream.

  • If you collect these elements by capturing the output in a variable, you always get a regular PowerShell array ([object[]]), except if there's only one element, which is captured as-is.

To prevent that - i.e., to output a collection as a whole - use:

Write-Output -NoEnumerate $t

A shorter and more efficient, but less obvious alternative is to wrap the collection in an auxiliary single-element array with the unary form of ,, the array-construction operator, which causes PowerShell to enumerate the outer array and output the collection within as-is:

, $t    # implicit output, no Write-Output needed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...