3

Anyone have any ideas why the following code would produce an error, see additional comments after the function for more details

function callee    ([Hashtable]$arg0) {
    [Hashtable]$hashtable = @{}
    $hashtable = $arg0
    $hashtable.add('passed', $True)
    # $hashtable                            ######## toggle this line
    $type = $hashtable.GetType()
    Write-Host "$type"
    return $hashtable
}

function caller {
    [Hashtable]$hashtable = @{'00'='0'}
    $hashtable = callee $hashtable        ##### returns error here
    $hashtable.add('returned', $True)
    $hashtable
}
caller

error message: Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Hashtable".

I receive the error on a variety of instances, I tried to narrow it down to an example that is easy to reproduce. It looks like it is changing the hashtable to an object array and that is why it won't return it? It allows me to modify the hashtable and return it but when I try to display it it changes it? This is the same effect I get when I start adding code to the callee function?

1 Answer 1

10

When you uncomment # $hashtable you're outputting two things from the function. The result of the function is everything 'output' from it, and PowerShell will automatically wrap multiple outputs into an array. The return statement is a short-circuit convenience and should not be confused with the only way to return a value from the function.

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

3 Comments

Agreed. I recommend against using the idiom return <expr> in PowerShell because it is misleading. It is functionally equivalent to Write-Output <expr>; return. Best just to put $hashtable as the last line of the function and call it good (just like the caller function does).
mind you sometimes just a call to some function might trigger output! hence be careful to assign the result to a variable. This way you would remove it from the output. That 'piece' here is critical thing to understand how powershell differs from other languages.

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.