如何从C#将参考参数传递给PowerShell脚本

时间:2020-03-11 23:27:16

标签: c# powershell

我似乎无法从C#将引用参数传递给PowerShell。我不断收到以下错误:

“ System.Management.Automation.ParentContainsErrorRecordException:无法处理参数'Test'上的参数转换。参数中应为引用类型。”

示例:

对于简单脚本:

Param (
[ref]
$Test
)

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

这是C#代码:

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

我尝试了AddParameter和AddArgument。

我要做的是首先将我的脚本创建为脚本块:

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

有帮助吗?

1 个答案:

答案 0 :(得分:1)

我似乎无法从C#向PowerShell中传递参考参数

使原始方法可行的唯一方法是在C#中创建[ref]实例 ,并传递那个,意味着创建System.Management.Automation.PSReference的实例并将其传递给您的.AddParameter()调用:

// 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}]");

以上产生Updated psRefVar: [Hello]


完整代码:

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}]");
      }

    }
  }
}