I have a need to use JsonConverter class in System.Text.Json in a module.
I would like the module to work in both Windows PowerShell 5.1 and PowerShell 7.1.4.
I have created a minimal cmdlet using the psmodule template and .NET CLI.
This is what is inside of my csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp2.0;net461</TargetFrameworks>
<AssemblyName>sopost</AssemblyName>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PowerShellStandard.Library" Version="5.1.0">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="System.Text.Json" Version="5.0.0" />
</ItemGroup>
</Project>
Steps to reproduce:
dotnet new -i Microsoft.PowerShell.Standard.Module.Template
dotnet new psmodule
dotnet add package System.Text.Json --version 5.0.0
Update targetframeworks to "netcoreapp2.0;net461"
Replace template cs file with contents from link below
dotnet build
dotnet publish -f netcoreapp2.0
dotnet publish -f net461
I can then import the module using PowerShell 7.1.4 from either of the publish directories and the module functions correctly.
PS C:\Dev\sopost\bin\Debug> Test-SampleCmdlet -FavoriteNumber 42 -FavoritePet Horse { "FavoritePet": "Horse", "FavoriteNumber": 42 }
I can import the module using Windows PowerShell 5.1 from the 461\publish directory, but the cmdlet will generate an exception when it actually hits the code that deals with System.Text.Json.
Test-SampleCmdlet : Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Here is a link to the single cs file that is the source for this cmdlet: cmdlet source
This is a very simple example of using System.Text.Json, but contains enough code to repro my issue.
Is there any easy way to accomplish what I'm trying to do? Is it possible to have a single module that can be used in both Windows PowerShell 5.1 and PowerShell 7.1.4 ? If yes, what is the directory layout of that module?
Is it possible to have a Windows PowerShell 5.1 module that uses System.Text.Json ?
Any advice / pointers would be greatly appreciated!