1

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?

1 Answer 1

5

A command would be Get-Date alone. When you use AddCommand that's what it expects. For example,

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

See AddCommand(String)

You have a script it, and it doesn't easily fit into AddCommand (because it isn't one). Tty AddScript instead:

ps.AddScript("(Get-Date).AddDays(1)").Invoke();
Sign up to request clarification or add additional context in comments.

2 Comments

What if I wanted to store that result in a variable?
As in store it in your class? You can still assign the return from Invoke() as you've done in your original, I just simplified it a bit for the sake of the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.