为什么此函数不能与管道变量一起使用?

Why won't this function work with a piped variable?

我创建了这个函数来解析特定文本的字段和 returns 自定义对象。

如果我使用语法 Get-MachineUser -VMArray $PassedArray 一切正常,但如果我使用管道传递数组 $PassedArray | Get-MachinesUser 则它不起作用。

我和团队中的某个人一起工作,我们发现当我们传递数组时它只处理数组中的最后一个条目。我不介意使用其他语法,但我很好奇我有什么错误导致管道无法工作。

function Get-MachinesUser{
    param (
        [parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [System.Object[]] $VMArray
    )
    foreach($vm in $VMArray){
        if($VM.Description -match '.*(ut[A-Za-z0-9]{5}).*'){
            [PSCustomObject]@{
            "Name" = $vm.Name  
            "User" = $Matches[1]
            }
        }
    }
}  

要支持管道输入,您的函数中需要一个进程块:

function Get-MachinesUser{
    param (
        [parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [System.Object[]] $VMArray
    )
    Process{
        foreach($vm in $VMArray){
            if($VM.Description -match '.*(ut[A-Za-z0-9]{5}).*'){
                [PSCustomObject]@{
                "Name" = $vm.Name  
                "User" = $Matches[1]
                }
            }
        }
    }  
}

Process

This block is used to provide record-by-record processing for the function. This block might be used any number of times, depending on the input to the function. For example, if the function is the first command in the pipeline, the Process block will be used one time. If the function is not the first command in the pipeline, the Process block is used one time for every input that the function receives from the pipeline.

Source: https://ss64.com/ps/syntax-function-input.html

(Note: The quote has been slightly amended as SS64 incorrectly indicated that the process block is not executed where there is no pipeline input, whereas in fact it still executes a single time).

您包含 ForEach 循环仍然是正确的,因为这意味着您在通过参数传递时支持数组输入。但是,为了在通过管道发送输入时处理所有输入,需要一个 Process { } 块。