【问题标题】:Import module in Powershell remote session using c#使用 c# 在 Powershell 远程会话中导入模块
【发布时间】:2014-07-08 06:14:32
【问题描述】:

我正面临一个让我头疼的问题(字面意思),我希望你能帮助我:

鉴于我的 Powershell 位于我的应用程序之外的其他服务器上,在 c# 中,您可以通过定义 WSManConnectionInfo 并在“运行空间”创建期间使用它来创建“Powershell 远程会话”。

类似:

var runspace = RunspaceFactory.CreateRunspace(WSManConnectionInfo);

但问题是:

当我们使用远程会话时,我们只能使用一些命令(并非所有命令都可用)。所以,你不能直接在远程会话中使用“Import-Module”命令。

所以我问你是否可以帮助我找到解决方案in c#(或只是一些提示)在远程会话中使用导入的模块。

我知道那里有很多解决方案(Pure Powershell 命令),但我还不足以在 c# 中转换这些解决方案。

【问题讨论】:

    标签: c# session powershell exchange-server


    【解决方案1】:

    嗯,我可以在远程会话中使用 Import-Module,例如:

    var connectionInfo = new WSManConnectionInfo(new Uri("http://foo.acme.com:5985"));
    var runspace = RunspaceFactory.CreateRunspace(connectionInfo);
    runspace.Open();
    
    using (var powershell = PowerShell.Create())
    {
        powershell.Runspace = runspace;
        powershell.AddScript("Import-Module PSCX");
        var results = powershell.Invoke();
        powershell.AddScript("Get-Uptime | Out-String");
        results = powershell.Invoke();
        foreach (var result in results)
        {
            Console.WriteLine(result);
        }
    
        runspace.Close();
    }
    

    输出:

    Uptime                                   LastBootUpTime
    ------                                   --------------
    10.20:21:06.6432615                      6/26/2014 6:29:00 PM
    

    您的模块是否可能是特定于位的,可能是仅加载到 x86 PowerShell 会话中的 32 位模块?默认会话为 64 位(假设远程操作系统为 64 位)。如果您的模块是 32 位特定的,请连接到 Microsoft.Powershell32 端点。

    var connectionInfo = new WSManConnectionInfo(new Uri("http://foo.acme.com:5985"), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell32", PSCredential.Empty);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 2014-08-25
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      • 2013-06-08
      相关资源
      最近更新 更多