使用命令行参数从 C# 执行 PowerShell 脚本 [英] Execute PowerShell Script from C# with Commandline Arguments

查看:35
本文介绍了使用命令行参数从 C# 执行 PowerShell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 C# 中执行 PowerShell 脚本.该脚本需要命令行参数.

I need to execute a PowerShell script from within C#. The script needs commandline arguments.

这是我目前所做的:

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"的内容.

scriptFile contains something like "C:\Program Files\MyProgram\Whatever.ps1".

该脚本使用命令行参数,例如-key Value",而 Value 可以是路径之类的东西,也可能包含空格.

The script uses a commandline argument such as "-key Value" whereas Value can be something like a path that also might contain spaces.

我不明白这个工作.有谁知道如何从 C# 中将命令行参数传递给 PowerShell 脚本并确保空格没有问题?

I don't get this to work. Does anyone know how to pass commandline arguments to a PowerShell script from within C# and make sure that spaces are no problem?

推荐答案

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

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

这篇关于使用命令行参数从 C# 执行 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆