且构网

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

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

更新时间:2023-02-22 10:18:49

尝试将脚本文件创建为单独的命令:

Try creating scriptfile as a separate command:

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