exceptions for Importing a Powershell Module from C#.Net RRS feed

  • Question

  • hi all,

    I write a code in C#.Net for importing a powerShell Module and calling its functions

    the code is:

    static public string test(string scriptText)
                InitialSessionState initial = InitialSessionState.CreateDefault();
                initial.ImportPSModule(new[] { "Microsoft.DHCP.PowerShell.Admin" });
                Runspace runspace = RunspaceFactory.CreateRunspace(initial);
                RunspaceInvoke invoker = new RunspaceInvoke(runspace);
                Collection<PSObject> results = invoker.Invoke(scriptText);
                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                return (stringBuilder.ToString());

    but in runnspace.open(); give this exception:


    1. Exception:Thrown: “cannot invoke this function because the current host does not implement it.” (System.Management.Automation.Host.HostException)

    and inCollection<PSObject> results = invoker.Invoke(scriptText); gives this exception:

    Exception:Thrown: The term 'Get-DHCPServer' 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.(system.management.Automation.CommandNotFoundException)

    Get-DHCPServer win-qkheb9s51i8 : is a function of this module .

    while I can Import this to PowerShell and call its functions correctly.

    how I can solve these exceptions?



    • Moved by Jason Dot Wang Monday, August 6, 2012 2:12 AM I have not make sure whether this thread is about Powershell or C#. (From:Visual C# General)
    Friday, August 3, 2012 6:05 AM


All replies