How to pass reference parameter to PowerShell script from C#

Viewed 605

I can't seem to be able to pass in a reference parameter to PowerShell from C#. I keep getting the following error:

"System.Management.Automation.ParentContainsErrorRecordException: Cannot process argument transformation on parameter 'Test'. Reference type is expected in argument."

Example:

For the simple script:

Param (
[ref]
$Test
)

$Test.Value = "Hello"
Write-Output $Test

And here's the C# code:

string script = {script code from above};
PowerShell ps = PowerShell.Create();
ps = ps.AddScript($"New-Variable -Name \"Test\" -Value \"Foo\""); // creates variable first
ps = ps.AddScript(script)
        .AddParameter("Test", "([ref]$Test)"); // trying to pass reference variable to script code

ps.Invoke(); // when invoked, generates error "Reference type is expected in argument

I've tried AddParameter as well as AddArgument.

What I have gotten to work is to create my script first as a script block:

ps.AddScript("$sb = { ... script code ...}"); // creates script block in PowerShell
ps.AddScript("& $sb -Test ([ref]$Test)"); // executes script block and passes reference parameter
ps.AddScript("$Test"); // creates output that shows reference variable has been changed

Any help?

1 Answers

I can't seem to be able to pass in a reference parameter to PowerShell from C#

The only way to make your original approach work is to create your [ref] instance in C# and pass that, which means creating an instance of System.Management.Automation.PSReference and passing that to your .AddParameter() call:

// Create a [ref] instance in C# (System.Management.Automation.PSReference)
var psRef = new PSReference(null);

// Add the script and pass the C# variable containing the
// [ref] instance to the script's -Test parameter.
ps.AddScript(script).AddParameter("Test", psRef);

ps.Invoke();

// Verify that the C# [ref] variable was updated.
Console.WriteLine($"Updated psRef: [{psRef.Value}]");

The above yields Updated psRefVar: [Hello]


Full code:

using System;
using System.Management.Automation;

namespace demo
{
  class Program
  {
    static void Main(string[] args)
    {
      var script = @"
        Param (
        [ref]
        $Test
        )

        $Test.Value = 'Hello'
        Write-Output $Test
        ";

      using (PowerShell ps = PowerShell.Create())
      {
        var psRef = new PSReference(null);
        ps.AddScript(script).AddParameter("Test", psRef);
        ps.Invoke();
        Console.WriteLine($"Updated psRef: [{psRef.Value}]");
      }

    }
  }
}
Related