Returned object from PowerShell using parameter ("By reference" parameter)?

I have one PowerShell (2.0) script calling another. I want to get back not only the main output, but also an additional object that I can use separately, for example. to display the summary line in the message.

Let Test2.ps1 be as the called script:

param([String]$SummaryLine) $Issues = "Potentially long list of issues" $SummaryLine = "37 issues found" $Issues 

And Test1.ps1 as a script that calls it:

 $MainOutput = & ".\Test2.ps1" -SummaryLine $SummaryOutput $MainOutput $SummaryOutput 

The result is simple:

 Potentially long list of issues 

Although the $ SummaryLine parameter is populated with Test2, the $ SummaryOutput remains undefined in Test1.

Defining $ SummaryOutput before calling Test2 does not help; it just saves the value assigned before calling Test2.

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

Is it possible in PowerShell to return a value to a parameter? If not, what are the workarounds? Directly assign a variable with parent scope in Test2?

+7
source share
2 answers

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

Test.ps1:

 Param ([ref]$OptionalOutput) "Standard output" $OptionalOutput.Value = "Optional Output" 

Run it:

 $x = "" .\Test.ps1 ([ref]$x) $x 

Here is an alternative that you might like better.

Test.ps1:

 Param ($OptionalOutput) "Standard output" if ($OptionalOutput) { $OptionalOutput | Add-Member NoteProperty Summary "Optional Output" } 

Run it:

 $x = New-Object PSObject .\Test.ps1 $x $x.Summary 
+9
source

Is it closer to what you want to do?

Test2.ps1

  $Issues = "Potentially long list of issues" $SummaryLine = "37 issues found" $Issues $SummaryLine 

Test1.ps1

  $MainOutput,$SummaryOutput = & ".\Test2.ps1" $MainOutput $SummaryOutput 

It:

  param([String]$SummaryLine) $Issues = "Potentially long list of issues" $SummaryLine = "37 issues found" $Issues 

It is irrational. You pass the parameter to $ SummaryLine, and then immediately replace it with the β€œ37 problems found”. This variable exists only in the area in which the called script is running. As soon as this script ends, it disappeared. If you want to use it later, you need to output it and save it in a variable in your script call.

+1
source

All Articles