Why won't this function work on a variable?

I created this function that parses a field for a specific text and returns a custom object.

Everything works fine if I use the syntax Get-MachineUser -VMArray $PassedArray

, but it doesn't work if I connect an array $PassedArray | Get-MachinesUser

.

I was working with someone on my team and we figured out when we pass an array, it only processes the last entry in the array. I don't mind using a different syntax, but I'm curious what kind of error I have that is causing the pipe to not work.

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]
            }
        }
    }
}  

      

+3


source to share


1 answer


To support pipeline input, you need a process block in your function:

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 write-by-write processing for a function. This block can be used any number of times, depending on the input of the function. For example, if the function is the first command in a pipeline, the Process block will be used once. If the function is not the first command in the pipeline, the Process block is used once for each input that the function receives from the pipeline.

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

(Note: The quote was slightly modified as SS64 incorrectly pointed out that a process block is not executed when there is no pipeline input, when in fact it is still executed once anyway).

You are still right to include the ForEach loop, as that means you are maintaining the array's input as it passed through the parameter. However, a block is required to process all input as it is sent down the pipeline Process { }

.

+6


source







All Articles