且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C#与命令行参数执行PowerShell脚本

更新时间:2023-02-22 10:36:39

尝试创建脚本文件作为一个单独的命令:

Try creating scriptfile as a separate command:

Command myCommand = new Command(scriptfile);

那么你就可以添加参数

then you can add parameters with

CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);

最后

pipeline.Commands.Add(myCommand);


下面是完整的,编辑code:


Here is the complete, edited code:

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 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();