【问题标题】:call a remote powershell script with parameters from c# program使用来自 c# 程序的参数调用远程 powershell 脚本
【发布时间】:2014-08-28 03:27:08
【问题描述】:

我有下一段代码可以调用远程 powershell 脚本(脚本在远程系统中),但我想向脚本发送参数:

c#方法:

public void RemoteConnection() 
{
   connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, credentials);
   runspace = RunspaceFactory.CreateRunspace(connectionInfo);
   runspace.Open();
   Pipeline pipeline = runspace.CreatePipeline(path);
   var results = pipeline.Invoke();
   foreach (PSObject obj in results)
    Console.WriteLine(obj.ToString());
}

我尝试使用 CommandParameter 发送参数,但收到错误消息:

Pipeline pipeline = runspace.CreatePipeline();
Command myCommand = new Command(path);
CommandParameter testParam0 = new CommandParameter("suma");
myCommand.Parameters.Add(testParam0);
CommandParameter testParam = new CommandParameter("x", "89");
myCommand.Parameters.Add(testParam);
CommandParameter testParam2 = new CommandParameter("y", "11");
myCommand.Parameters.Add(testParam2);
pipeline.Commands.Add(myCommand);

错误信息:

{"Cannot perform operation because operation \"NewNotImplementedException at offset 76 in file:line:column <filename unknown>:0:0\r\n\" is not implemented."}

我可以通过这种方式调用我的 powershell 脚本(在我的远程系统中):

PS C:\grace\powershell> .\script1.ps1  -suma -x 9 -y 19
28
PS C:\grace\powershell> .\script1.ps1  -suma "9" "19"
28

如何通过 c# 程序参数发送我的 powershell 脚本?

【问题讨论】:

  • 过去有人问过这个问题,通过查看这个答案来了解如何在此处实现:stackoverflow.com/questions/10260597/…
  • @MattGartman 我按照帖子的建议尝试过,但我总是收到错误消息“无法执行操作,因为操作...”

标签: c# powershell powershell-remoting


【解决方案1】:

它是如何为我工作的:

public void RemoteConnection() 
{
  connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, credentials);
        runspace = RunspaceFactory.CreateRunspace(connectionInfo);
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline(path);

        Command myCommand = new Command(path);
        CommandParameter testParam0 = new CommandParameter("-suma");
        myCommand.Parameters.Add(testParam0);

        CommandParameter testParam = new CommandParameter("x", "34");
        myCommand.Parameters.Add(testParam);
        CommandParameter testParam2 = new CommandParameter("y", "11");
        myCommand.Parameters.Add(testParam2);

        pipeline.Commands.Add(myCommand);
        var results = pipeline.Invoke();
        foreach (PSObject obj in results)
          Console.WriteLine(obj.ToString());
}

注意,我将路径发送到 CreatePipeline 并创建一个新命令(可能需要进一步审查)

【讨论】:

    【解决方案2】:

    也许这可以帮助你: http://com2kid.wordpress.com/2011/09/22/remotely-executing-commands-in-powershell-using-c/

    将所有命令设置在一起。

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 1970-01-01
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 2011-01-28
      • 2012-02-06
      相关资源
      最近更新 更多