Nathan McKaskle Nathan McKaskle - 1 year ago 102
PowerShell Question

Running Basic Powershell Commands in C# Error cmdlet not found

I have a C# console program and I want to run powershell commands NOT SCRIPTS, but no matter what command I try to run in the powershell runspace, it gets an error saying cmdlet not found. It can be as simple as the following:

static void Main(string[] args)
using (Runspace runspace = RunspaceFactory.CreateRunspace())
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
var result = ps.Invoke();

catch (Exception ex)
Console.WriteLine("Error: " + ex.ToString());

I can type this command at the powershell command line and it runs perfectly fine. I don't have to add any modules to run it. What am I missing?

Answer Source

A command would be Get-Date alone, when you use AddCommand that's what it expects. e.g.

ps.AddCommand("Get-Date").AddParameter("Format", "u").Invoke();


What you have is a script and doesn't easily fit into AddCommand (because it isn't one), try AddScript instead: