1

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
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thanks! So all I had missing was $myOutput.value = … in MyExtensions.psm1 and the call should be if($myTypeItem.TryGetValue($myInput, [ref]$value).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.