为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
大话西游666 2019-11-15 15:10:07
使用命令行参数从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贡献1825条经验 获得超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();



查看完整回答
反对 回复 2019-11-16
  • 3 回答
  • 0 关注
  • 388 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信