Archives

Archives / 2009 / March
  • PowerShell: Return values from a function through reference parameters

    PowerShell has a special [ref] keyword to specify which parameters are used in a fuction to return values. It's usage is not directly clear however.

    If the type of the variable to update is a value type, use the [ref] keyword in the declaration of the function parameter, this specifies that a "pointer" to the variable will be passed.

    To pass the "pointer" to the variable, use ([ref]$variable) to create the pointer, and pass this as parameter. To set the value of the value variable pointed to by the "pointer", use the .Value field.

    Simple example to show what [ref] does:

    C:\Program Files\PowerGUI> $zz = "hoi"
    C:\Program Files\PowerGUI> $xz = [ref]$zz
    C:\Program Files\PowerGUI> $xz
    Value
    -----
    hoi

    C:\Program Files\PowerGUI> $xz.Value = "dag"
    C:\Program Files\PowerGUI> $zz
    dag 

    This is only required for value types, not is the type is a referece type like for example Hashtable.

    Some sample code:

    function fn
    {
    param
    (
    [ref]$arg1,
    [ref]$arg2,
    $arg3
    )

    $arg1.Value = 1
    $arg2.Value = "overwrite"
    $arg3.key = "overwrite hash value"
    }

    $x = 0
    $y = "original"
    $z = @{"key" = "original hashvalue"}
    $x
    $y
    $z.key
    fn -arg1 ([ref]$x) -arg2 ([ref]$y) -arg3 $z
    $x
    $y
    $z.key