2

リモート マシンで Powershell コマンドを実行したい。これは私が使用している方法です (localhost:131 は、リモート マシンのポート 5985 へのトンネルを使用するためです)。

  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.

メソッドは単純なコマンドでうまく機能し、実行したいコマンドはリモートマシンで実行しても問題ありません。

前もって感謝します。

よろしく、ドゥサン

4

2 に答える 2

0

powershell.AddParameter()メソッドを使用して、コマンドのパラメーターを追加する必要があります。AddCommand() 呼び出しでは、コマンドのみを指定する必要があります: コマンドレット名、関数名、スクリプトへのパスなど。ドキュメントから:

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-Process");
ps.AddArgument("wmi*");
ps.AddCommand("Sort-Object");
ps.AddParameter("descending");
ps.AddArgument("id");
于 2012-04-17T16:14:29.020 に答える