Home > database >  Powershell Function - how to deal with multiple return values?
Powershell Function - how to deal with multiple return values?

Time:04-02

I have a Powershell function with multiple return values. But one value should only be returned when it is not empty.

if ($value4 -ne '')
{
    return   $value4
}

return $value1, $value2, $value3

That does not work. How can I do that?

Thanks for your help!

CodePudding user response:

You can only use return once. The use of if/else is to determine which of two (or more) outcomes should be derived from a test.

The correct way to write your return statement in conjunction with the if/else is as follows:

if ($null -ne $value4)
{
    return $value1, $value2, $value3, $value4
}
else
{
    return $value1, $value2, $value3
}

There should be no code following that closing Else statement.

PS - I have opted to use $null value check instead of String.Empty like you have. Using '' is the C# equivalent of String.Empty.

So you could write it like this:

if ($value4 -ne String.Empty)
{
    return $value1, $value2, $value3, $value4
}
else
{
    return $value1, $value2, $value3
}

CodePudding user response:

As others have noted, return happens once: it terminates the function and returns the specified object(s) into the pipeline to the caller.

In your case this is indeed multiple objects. Your example suggests you're reaching for a pattern to decide to add another object to the return, as if you're accumulating the list along the way, and you can do that.

$return = @($value1, $value2, $value3)

if ($null -ne $value4)
{
    $return  = $value4
}

return $return

The @() en-listing operator is, in this example, syntactic sugar to state that we're creating a 3 element list. It is not strictly needed here because the comma operator does create a list even if it was omitted.

Where @() would be necessary is if we needed to create a single element list to append to.

$return = 1
$return  = 2

$return ====> 3

SO

$return = @(1)
$return  = 2

$return ====> @(1,2)
  • Related