Question

I am hosting powershell within my app and have set up a restricted runspacepool, which is basically empty (to the best of my knowledge).

public class MyPowerShell : IDisposable
{
    private RunspacePool _runspacePool;
    private PowerShell _shell;

    public MyPowerShell()
    {
        try
        {
            var initialSessionState = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer);

            _runspacePool = RunspaceFactory.CreateRunspacePool(initialSessionState);

            _shell = PowerShell.Create();
            _shell.RunspacePool = _runspacePool;
            _shell.RunspacePool.Open();

            _shell.AddCommand("Import-Module").AddParameter("Assembly", Assembly.GetExecutingAssembly());
            _shell.Invoke();
            _shell.Commands.Clear();
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    public void Dispose()
    {
        _shell.RunspacePool.Close();
        _shell.Dispose();
    }

    public string[] Exec(string commandText)
    {
        var results = new List<string>();

        try
        {
            _shell.AddScript(commandText);
            foreach (var str in _shell.AddCommand("Out-String").Invoke<string>())
            {
                results.Add(str);
            }
        }
        catch (Exception ex)
        {
            results.Add(ex.Message);
        }
        return results.ToArray();
    }

}

obviously, when I run this code ...

        _shell.AddCommand("Import-Module").AddParameter("Assembly", Assembly.GetExecutingAssembly());
        _shell.Invoke();
        _shell.Commands.Clear();

it fails because there is no "Import-Module" cmdlet available. So, my question is how can I import a module without the "Import-Module" cmdlet being available?

This is the error message I am getting ...

The term 'Import-Module' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Was it helpful?

Solution

I have found a solution, can't remember where I did now and I'd actually forgotten I'd asked this question! Anyway, here it is for the benefit of anyone with the same problem.

var initialSessionState = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer);
initialSessionState.ImportPSModule(new [] { "ModuleName1", "ModuleName2" });

I can't actually see which module I was trying to import when I asked this question, but I have successfully used the above code for using AppFabric administration powershell cmdlets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top