c# - 使用 c# 程序的参数调用远程 powershell 脚本

标签 c# powershell powershell-remoting

我有下一段代码可以调用远程 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

如何为我的 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);

        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 并创建一个新命令(可能需要进一步审查)

关于c# - 使用 c# 程序的参数调用远程 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25531984/

相关文章:

Powershell v2 远程处理和委派

c# - 从字典中取出 n 个元素

c# - Uri 为 WPF 样式 uri 抛出无效端口

c# - 在 C# 中读取 Powershell 进度条输出

powershell - Powershell用arg启动/停止

unit-testing - 如何在powershell中进行TDD和单元测试?

powershell - 在远程 session 中执行时,将PowerShell stdout重定向到文件

c# - 覆盖显式接口(interface)实现?

c# - OpenGL闪烁问题

powershell - 捕获 RPC 服务器不可用错误 HRESULT : 0x800706BA