7

I want to write PowerShell in C#. There is a useful link from red-gate.com which describes the steps for the process. The author uses the .Net Framework as Class library project. I have no problems with that, however, I would like to write my functions also for .Net Core in order to make them also cross-platform functional. I created a new project with the target framework netcoreapp3.1. When I install System.Management.Automation 7.1.2 I get the error:

Error   NU1202  Package System.Management.Automation 7.1.2 is not compatible with netcoreapp3.1 (.NETCoreApp,Version=v3.1). Package System.Management.Automation 7.1.2 supports: net5.0 (.NETCoreApp,Version=v5.0)

I am confused with the supported .NETCoreApp v5.0. With this link https://dotnet.microsoft.com/download there is .NET v5.0 and .NET Core 3.1. When I target net5.0 I get the error that the reference assemblies are not found but I installed the .NET 5.0 SDK.

C:\Users\Alex_P>dotnet --list-sdks
3.1.403 [C:\Program Files\dotnet\sdk]
5.0.201 [C:\Program Files\dotnet\sdk]

My question, how can I use System.Management.Automation in a .NET Core (cross-platform project) to write PowerShell functions?

Alex_P
  • 2,580
  • 3
  • 22
  • 37
  • It is best to use Net 4.7.2 or later which give option to target different versions of Net and Core from same source code. You also need to install the core version which may not be in the machine. – jdweng Mar 12 '21 at 21:54

1 Answers1

7

Even though, unfortunately, the System.Management.Automation package's NuGet page doesn't mention it, this package is not meant to be used directly.

Instead, use one of the packages described in this answer, depending on your use case.

To target PowerShell (Core) 7+, use the Microsoft.PowerShell.SDK package.

  • To determine what specific .NET (Core) runtime a given package version must be combined with at a minimum, select the package version of interest on the linked page, expand the Dependencies section, and consult the first entry; e.g., for package version 7.1.3 the minimum required .NET (Core) runtime is net5.0
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thanks, @Alex_P - I've updated to the answer to show how to generally determine the minimum runtime version required for a given package version. – mklement0 May 09 '21 at 21:26