2012-04-17 232 views
2

我想在远程计算机上运行Powershell命令。这是方法我使用(本地主机:131是我用隧道远程机器的端口5985):远程运行powershell命令时出错

public string RunRemotePowerShellCommand(string command) 
    { 
      System.Security.SecureString password = new System.Security.SecureString(); 
      foreach (char c in _password.ToCharArray()) 
      { 
       password.AppendChar(c); 
      } 

      string schema = "http://schemas.microsoft.com/powershell/Microsoft.Powershell"; 

      WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, 
       "localhost", 131, "/wsman", schema, new PSCredential(_domain + @"\" + _userName, password)); 

      using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo)) 
      { 
       remoteRunspace.Open(); 
       using (PowerShell powershell = PowerShell.Create()) 
       { 
        powershell.Runspace = remoteRunspace; 
        powershell.AddCommand(command); 
        powershell.Invoke(); 

        Collection<PSObject> results = powershell.Invoke(); 

        // convert the script result into a single string 
        StringBuilder stringBuilder = new StringBuilder(); 
        foreach (PSObject obj in results) 
        { 
         stringBuilder.AppendLine(obj.ToString()); 
        } 
        return stringBuilder.ToString(); 
       } 
      } 
    } 

我试图运行下面的命令:

D:\FolderName\scriptName.ps1 -action editbinding -component "comp1","comp2","comp3","comp4" 

像这样:

RunRemotePowerShellCommand(@"D:\FolderName\scriptName.ps1 -action editbinding -component ""comp1"",""comp2"",""comp3"",""comp4"""); 

,但我得到:

Error: System.Management.Automation.RemoteException: The term 'D:\FolderName\scriptName.ps1 -action editbinding -component "comp1","comp2","comp3","comp4"' is not recognized as a name of cmdlet, function, script file, or operable program. Check the spelling of the name, or if the path is included, verify that the path is correct and try again. 

这个方法对于简单的命令可以正常工作,并且当我在远程机器上运行它时,我想要运行的命令是正常的。

在此先感谢。

问候, 杜尚

回答

0

您需要使用powershell.AddParameter()方法添加的参数为你的命令。 AddCommand()调用应仅命名命令:cmdlet名称,函数名称,脚本路径等。从文档:

PowerShell ps = PowerShell.Create(); 
ps.AddCommand("Get-Process"); 
ps.AddArgument("wmi*"); 
ps.AddCommand("Sort-Object"); 
ps.AddParameter("descending"); 
ps.AddArgument("id"); 
+0

谢谢你的回答,我试过这个,得到错误:“由于当前主机没有实现它,所以不能调用这个函数。”我尝试了更多的东西,问题似乎与远程脚本的路径(尽管它是正确的)。 – 2012-04-18 09:27:32

0

我有类似的要求。

我的解决方案是在C#代码中创建一个powershell函数,并在PowerShell远程会话中使用它。

using System; 
using System.Management.Automation; 

namespace PowerShellTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string func = @"function Test { Write-Host 'hello' };"; 
      PowerShell ps = PowerShell.Create(); 
      ps.AddScript(func); 
      ps.Invoke(); 
      ps.AddCommand("Test"); 
      ps.Invoke(); 
      Console.WriteLine("Successfully executed function"); 
      Console.ReadLine(); 
     } 
    } 
}