c# - 远程运行 powershell 命令时出错

标签 c# powershell powershell-remoting

我想在远程机器上运行 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.

该方法适用于简单的命令,当我在远程机器上运行时,我想运行的命令也可以。

提前致谢。

问候, 杜桑

最佳答案

您需要使用 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");

关于c# - 远程运行 powershell 命令时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10189301/

相关文章:

list - 在 PowerShell 中创建成对字符串值列表

Powershell Copy-Item - 仅当文件存在于目标中时才排除

powershell - 在新的 Azure VM 上启用 PowerShell 远程处理

c# - 如何从 Azure 移动服务返回异常

c# - 搜索大型 Excel 文件并高效处理大量数据

c# - 高压缩图像

PowerShell 通过引用传递对我不起作用

powershell - 使用 PowerShell 重命名文件时,如何处理带有 "["的文件名?

powershell - 阻止 Powershell 退出

c# - OracleDataAdapter,Fill 方法挂起,如何处理连接终止/断开/切断?