簡體   English   中英

如何將引用參數從 C# 傳遞給 PowerShell 腳本

[英]How to pass reference parameter to PowerShell script from C#

我似乎無法從 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# 中創建您的[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}]");
      }

    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM