Nathan McKaskle Nathan McKaskle - 3 months ago 23
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)
{
try
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand("(Get-Date).AddDays(1)");
var result = ps.Invoke();

Console.WriteLine(result);
}
}
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

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

See https://msdn.microsoft.com/en-us/library/dd182430(v=vs.85).aspx

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

ps.AddScript("(Get-Date).AddDays(1)").Invoke();