powershellfunctionreturn-valuereturn-type

How to define the return type / OutputType of a function


Why is the following changing type?

function SomeFunction($SomeParameter){
    return $SomeParameter
}

I guess I need to set a return type, but how?

An example is using:

$NewFolder=Join-Path $CurrentFolder -ChildPath $FolderName
$Tmp=SomeFunction($NewFolder)

Now $Tmp is an array and not just a path


Solution

  • Your issue is per "design". PowerShell will return an array in chunks so that it can be forwarded the PowerShell pipeline.

    Example:

     SomeFunction -SomeParameter @(1,2,3,4) | Where-Object { $_ -gt 2 }
    

    Without this behavior pipelining the output of the function to another function/cmdlet won't be possible.

    If you want to return an array you can change to code to:

     function SomeFunction($SomeParameter){
        <#
         # Through the unary operator we can return an array with one entry.
         # This entry contains the original array.
         #>
        ,$SomeParameter
    }
    

    Another option would be the use of @() when at the calling side:

    function SomeFunction($SomeParameter){
        # return to pipelin
        $SomeParameter
    }
    
    $array = @(SomeFunction -SomeParameter 1,2,3,4)
    

    There is also this reddit answer explaining the behavior in more detail.

    Hope that helps.