使用命令行参数从C#执行PowerShell脚本我需要在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 scriptresults = pipeline.Invoke();scriptFile包含类似“C:\ Program Files \ MyProgram \ Whatever.ps1”的内容。该脚本使用命令行参数,例如“-key Value”,而Value可以是类似于也可能包含空格的路径。我不这样做。有谁知道如何从C#中将命令行参数传递给PowerShell脚本并确保空格没有问题?
3 回答
互换的青春
TA贡献1797条经验 获得超6个赞
尝试将scriptfile创建为单独的命令:
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();RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);Pipeline pipeline = runspace.CreatePipeline();//Here's how you add a new script with argumentsCommand myCommand = new Command(scriptfile);CommandParameter testParam = new CommandParameter("key","value");myCommand.Parameters.Add(testParam);pipeline.Commands.Add(myCommand);// Execute PowerShell scriptresults = pipeline.Invoke();
宝慕林4294392
TA贡献2021条经验 获得超8个赞
有没有机会我可以更清楚地了解Commands.AddScript方法的传递参数?
C:\ Foo1.PS1 Hello World Hunger C:\ Foo2.PS1 Hello World
scriptFile =“C:\ Foo1.PS1”
parameters =“parm1 parm2 parm3”...可变长度的参数
解决了这个问题......将null作为名称,将param作为值传递给CommandParameters集合
这是我的功能:
private static void RunPowershellScript(string scriptFile, string scriptParameters){ RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); Pipeline pipeline = runspace.CreatePipeline(); Command scriptCommand = new Command(scriptFile); Collection<CommandParameter> commandParameters = new Collection<CommandParameter>(); foreach (string scriptParameter in scriptParameters.Split(' ')) { CommandParameter commandParm = new CommandParameter(null, scriptParameter); commandParameters.Add(commandParm); scriptCommand.Parameters.Add(commandParm); } pipeline.Commands.Add(scriptCommand); Collection<PSObject> psObjects; psObjects = pipeline.Invoke();}
- 3 回答
- 0 关注
- 347 浏览
添加回答
举报
0/150
提交
取消