我想将3个参数从C#传递到powershell函数,但输出显示同一行中的所有参数。如何解决?
这是Powershell代码
private byte[] RemoveSignatures(byte[] stream)
{
string stream2 = Encoding.UTF8.GetString(stream);
stream2 = stream2.Replace("\0", "");
Regex x = new Regex("(\\<SOAP-ENV:Header\\>)(.*?)(\\</SOAP-ENV:Header\\>)");
string repl = "";
stream2 = x.Replace(stream2, "$1" + repl + "$3");
byte[] streamNuevo = Encoding.ASCII.GetBytes(stream2);
return streamNuevo;
}
这是c#代码。
param (
[string] $param1,
[string] $param2,
[string] $param3
)
# begin
function AddStuff($x, $y ,$z)
{
"x: $x;"
"y: $y;"
"z: $z;"
}
AddStuff $param1, $param2, $param3
# end
当我运行它时,显示这样的MessageBox。
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
string scriptfile = @"C:\Users\test2.ps1";
Command myCommand = new Command(scriptfile);
CommandParameter testParam1 = new CommandParameter("param1", "paramvalue1");
CommandParameter testParam2 = new CommandParameter("param2", "paramvalue2");
CommandParameter testParam3 = new CommandParameter("param3", "paramvalue3");
myCommand.Parameters.Add(testParam1);
myCommand.Parameters.Add(testParam2);
myCommand.Parameters.Add(testParam3);
pipeline.Commands.Add(myCommand);
Collection<PSObject> results = pipeline.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
MessageBox.Show(stringBuilder.ToString());
那是错的。为什么它不像这样显示。
x: paramvalue1 paramvalue2 paramvalue3;
y:
z:
答案 0 :(得分:2)
在PowerShell脚本中,调用AddStuff时不要使用逗号分隔参数:
AddStuff $param1 $param2 $param3
这样做的时候
AddStuff $param1, $param2, $param3
您实际上是在创建包含$ param1,$ param2和$ param3的PowerShell array;然后将此数组传递到AddStuff的第一个参数($ x),这就是为什么您得到意外输出的原因。
如果您首先在PowerShell ISE中测试PowerShell脚本,则在担心如何从C#调用脚本之前,可以更轻松地发现这类问题。