Return object from PowerShell using a parameter (“By Reference” parameter)?

Question:

I have one PowerShell (2.0) script calling another. I want to receive back not only the main output, but an additional object that I can use separately, e.g. to display a Summary Line in a message.

Let’s have Test2.ps1 as the script being called:

And Test1.ps1 as the script that calls it:

The output is simply:

Although the parameter $SummaryLine is filled in by Test2, $SummaryOutput remains undefined in Test1.

Defining $SummaryOutput before calling Test2 doesn’t help; it just retains the value assigned before calling Test2.

I’ve tried setting up $SummaryOutput and $SummaryLine as a [ref] variables (as one can apparently do with functions), but the $SummaryOutput.Value property is $null after calling Test2.

Is it possible in PowerShell to return a value in a parameter? If not, what are the workarounds? Directly assigning a parent-scoped variable in Test2?

Answer:

Ref should work, you don’t say what happened when you tried it. Here is an example:

Test.ps1:

Run it:

Here is an alternative that you might like better.

Test.ps1:

Run it:

Source:

Return object from PowerShell using a parameter (“By Reference” parameter)? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply