我需要从 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();
scriptFile 包含类似“C:\Program Files\MyProgram\Whatever.ps1”的内容。
该脚本使用命令行参数,例如“-key Value”,其中 Value 可以是类似路径的东西,也可能包含空格。
我无法让这个工作。有谁知道如何从 C# 中将命令行参数传递给 PowerShell 脚本并确保空格没有问题?
尝试将脚本文件创建为单独的命令:
Command myCommand = new Command(scriptfile);
然后你可以添加参数
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
最后
pipeline.Commands.Add(myCommand);
这是完整的、编辑过的代码:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
results = pipeline.Invoke();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)