我似乎无法从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
需要帮忙吗?