简体   繁体   中英

Import module in Powershell remote session using c#

I am facing a problem that cause me headaches (literally), I hope if you can help me with it :

Given that my Powershell is on an other server than my application, in c#, you can create a "Powershell remote session" by defining an WSManConnectionInfo and using this during the "runspace" creation.

Somthing like :

var runspace = RunspaceFactory.CreateRunspace(WSManConnectionInfo);

But the problem is :

When we are working with the remote session, we can only use some commands(Not all the commands are available). So, you can't use the "Import-Module" command directly in the remote session.

So I am asking you if you can help me to find a solution in c# (or just some hint) to use imported module in the remote session.

I know there's a lot of solution out there (Pure Powershell command), but I am just not good enough to convert these solutions in c#.

Hmm, I am able to use Import-Module in a remote session eg:

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();
}

That outputs:

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

Is it possible that your module is bit-specific, perhaps a 32-bit module that only loads into an x86 PowerShell session? The default session will be 64-bit (assuming the remote OS is 64-bit). If it turns out that your module is 32-bit specific, connect to the Microsoft.Powershell32 endpoint.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM