Monday, December 9, 2019

The possibly best way to return value from function in PowerShell

"Return value" from function is tricky in PowerShell.

By default, PowerShell functions work so that when executed, they write to the $Result array all the values that were displayed during the function’s operation.

This makes "Return value" useless.

How should we handle "return value" of function then? I don't want to use global variable, so, reference variable seems the only choice, as it chooses the correct data type automatically.

Below are some sample code. Please let me know if you have better idea!

  • Sample code 1
Function TestFunctionReturnValue{
    [cmdletbinding()]
    param(
        [Parameter(Mandatory=$true)][AllowEmptyString()][string]$Para1,
        [ref]$ParaReturnObject
    )
    $ParaReturnObject.Value = $false
    if ($Para1){
        $ParaReturnObject.Value  = $true
    }
}

$testResult1 = $null
$testResult2 = $null

TestFunctionReturnValue "hello" ([ref]$testResult1)
TestFunctionReturnValue "" ([ref]$testResult2)

Write-Host "testResult1 = $testResult1"
Write-Host "testResult2 = $testResult2"

$testResult1.GetType().FullName
$testResult2.GetType().FullName

Result:
  • Sample code 2
Function TestFunctionReturnValue2{
    [cmdletbinding()]
    param(
        [Parameter(Mandatory=$true)][AllowEmptyString()][string]$Para1,
        [ref]$ParaReturnObject
    )
    $ParaReturnObject.Value = 100
    if ($Para1){
        $ParaReturnObject.Value  = 200
    }
}

$testResult1 = $null
$testResult2 = $null

TestFunctionReturnValue2 "hello" ([ref]$testResult1)
TestFunctionReturnValue2 "" ([ref]$testResult2)

Write-Host "testResult1 = $testResult1"
Write-Host "testResult2 = $testResult2"

$testResult1.GetType().FullName
$testResult2.GetType().FullName

Result:

1 comment: