0

I'm currently using visual studio 2022 and System.Management.Automation version 7.1 I want to build an app that could run a PowerShell Script and return a string of result

Here is My Code

public string GetNetAdapterList()
    {

        Runspace rs = RunspaceFactory.CreateRunspace();
        rs.Open();
        Pipeline pipeline = rs.CreatePipeline();
        pipeline.Commands.Add("Rename-LocalUser");
        pipeline.Commands.Add("Out-String");
        Collection<PSObject> results = pipeline.Invoke();
        rs.Close();
        StringBuilder stringBuilder = new StringBuilder();  

        foreach (PSObject ps in results)
        {
            stringBuilder.AppendLine(ps.ToString());
        }
        return stringBuilder.ToString();

    }

after I run this app I Get Command Not Found Exception how to solve this problem?

Full error :

An exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll but was not handled in user code. The term 'Rename-LocalUser ' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

mklement0
  • 382,024
  • 64
  • 607
  • 775
SecGen Unity
  • 35
  • 1
  • 5
  • which commands are available in the powershell sdk in c# ? @mklement0 – SecGen Unity Jul 04 '21 at 15:43
  • 1
    That depends on what SDK package you're using - see [this answer](https://stackoverflow.com/a/58211901/45375). Note that using the `System.Management.Automation` package is _not_ recommended. If you use `PowerShellStandard.Library`, you're relying on the machine's regular PowerShell installation, which should give you the same commands as in an interactive session. – mklement0 Jul 04 '21 at 15:49
  • @SecGenUnity are you sure that once you removed the space as mklement0 suggested you did not receive a different exception, perhaps something like a `ParameterBindingException`? – Daniel Jul 04 '21 at 16:02
  • @Daniel same error occurs . – SecGen Unity Jul 04 '21 at 16:04
  • 1
    @Daniel, I've removed the trailing space from the question, to avoid a distraction, but you are correct: if the command _were_ available, you'd get the type of error you describe (`Rename-LocalUser : Parameter set cannot be resolved using the specified named parameters.`) – mklement0 Jul 04 '21 at 16:55
  • seems like a dup https://stackoverflow.com/questions/6266108/powershell-how-to-import-module-in-a-runspace – Garr Godfrey Jul 04 '21 at 17:14
  • see above. need to import the module. – Garr Godfrey Jul 04 '21 at 17:14

0 Answers0