c# - 如何从 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#中创建您的[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}]");
}
}
}
}
推荐阅读
- websphere-liberty - 如何从 Liberty 的响应中消除“Content-Language”标头?
- azure-devops - 在 Azure devops 发布管道中启用对 SQL Server 的公共访问
- java - 为 Dataflow flex 启动器设置网络标签
- android - 如何解决增量 Lint 的问题?
- html - 如何在标题中设置边距底部?
- python - 'CalledProcessError' 退出状态 128. Git 描述错误并在 sh() 中使用 sed 将 '/' 替换为 '__'
- javascript - TypeError:无法在“WebGLRenderingContext”上执行“texImage2D”:重载解析失败
- javascript - 如何将所有内容自动适合组件安装页面?
- mv - 访问失败错误 - 尝试移动文件时没有这样的文件
- python - 如何解决 Keyerror(return self.attrs[key]) 以在 Python 上提取数据?