首页 > 解决方案 > 如何从 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

有什么帮助吗?

标签: c#powershell

解决方案


我似乎无法从 C# 将引用参数传递给 PowerShell

使您的原始方法起作用的唯一方法是在 C#中创建您的[ref]实例并传递that,这意味着创建一个实例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}]");
      }

    }
  }
}

推荐阅读