Search code examples
c#visual-studio-2019powershell-5.0

Trying to get powershell working within C#/Visual Studio


I was trying to learn how to use powershell within C# I was following this tutorial

However when I run it I get this error:

Unhandled exception. System.InvalidProgramException: Common Language Runtime detected an invalid program. at System.Management.Automation.PowerShell.Create() at desktopAdmin365.Program.Main(String[] args) in C:\Users\ncox\source\repos\desktopAdmin365\Program.cs:line 11

C:\Users\ncox\source\repos\desktopAdmin365\bin\Debug\netcoreapp3.0\desktopAdmin365.exe (process 17464) exited with code -532462766.

I am sure I'm missing something when including references/dependencies from the solutions explorer but I am not having any luck with google finding out which one

Here is the code

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;
namespace desktopAdmin365
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PowerShell PowerShellInstance  = PowerShell.Create())
            { 
                PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; " +
                "$d; $s; $param1; get-service");
            }
        }
    }
}

Solution

  • If you look at your dependencies in the project, you'll likely see a warning about the package being restored using .NETFramework and possibly not being compatible.

    Your project is .NET core, so you might need to install Powershell Core instead.

    Alternatively, switch to a .net framework solution and it will work.