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
[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
[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:
ReplyDeleteSuch an informative post. Thank you for sharing
Office 365 Project Online