Search code examples
powershell-5.0

How to return a reference value with a method from an extended Powershell object?


I'm trying to extend a Powershell object with a method that

  1. returns a true or false to indicate success
  2. outputs a value by reference ([ref])

I have in my module MyExtensions.psm1.

Update-TypeData -TypeName [MyType] -MemberType ScriptMethod -memberName TryGetValue -force -value `
{
    param(
        $myInput,
        [ref]$myOutput
    )

    try
    {
        # do something with $myInput
        $myOutput = …
        return $true
    }
    catch
    {
        return $false
    }

} 

The goal is to be able to write in a script or in another module:

Import-Module MyExtensions
$myInput = …
$value = $null
if($myTypeItem.TryGetValue($myInput, $value)
{
  # I know that the $value is good
}

Solution

  • Using argument by reference (you just miss $myOutput.Value ="")

    function addition ([int]$x, [int]$y, [ref]$R)
    {
     $Res = $x + $y
     $R.value = $Res
    }
    
    $O1 = 1
    $O2 = 2
    $O3 = 0
    addition $O1 $O2 ([ref]$O3)
    Write-Host "values from addition $o1 and $o2 is $o3"
    

    A more comple answer here.