使用命令行参数从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 回答
holdtom
TA贡献1805条经验 获得超10个赞
尝试将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();
- 3 回答
- 0 关注
- 1383 浏览
添加回答
举报
0/150
提交
取消