我需要在C#中执行PowerShell脚本.该脚本需要命令行参数.
这是我到目前为止所做的:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(scriptFile);
// Execute PowerShell script
results = pipeline.Invoke();
Run Code Online (Sandbox Code Playgroud)
scriptFile包含类似"C:\ Program Files\MyProgram\Whatever.ps1"的内容.
该脚本使用命令行参数,例如"-key Value",而Value可以是类似于也可能包含空格的路径.
我不这样做.有谁知道如何从C#中将命令行参数传递给PowerShell脚本并确保空格没有问题?
我正在从C#应用程序运行Powershell测试脚本.由于cmdlet错误导致pipe.Invoke()抛出异常,脚本可能会失败.
我能够捕获关于异常所需的所有信息,但我希望能够显示脚本的输出到那时为止.我没有运气,因为抛出异常时结果似乎为null.
有什么我想念的吗?谢谢!
m_Runspace = RunspaceFactory.CreateRunspace();
m_Runspace.Open();
Pipeline pipe = m_Runspace.CreatePipeline();
pipe.Commands.AddScript(File.ReadAllText(ScriptFile));
pipe.Commands.Add("Out-String");
try {
results = pipe.Invoke();
}
catch (System.Exception)
{
m_Runspace.Close();
// How can I get to the Powershell output that comes before the exception?
}
Run Code Online (Sandbox Code Playgroud)