I have a C# project that creates a PowerShell instance that invokes a script. However, the published output does not run.
My project definition is:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.3.4" />
</ItemGroup>
<ItemGroup>
<None Update="Script.ps1">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
My MRE c# code is:
namespace ConsoleApp1;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
internal class Program
{
private static async Task Main(string[] args)
{
var initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.LanguageMode = PSLanguageMode.FullLanguage;
using var runSpace = RunspaceFactory.CreateRunspace(initialSessionState);
using var powerShell = PowerShell.Create();
runSpace.Open();
powerShell.Runspace = runSpace;
var script = await File.ReadAllTextAsync(@"Script.ps1");
powerShell.AddScript(script);
await powerShell.InvokeAsync().ConfigureAwait(false);
}
}
The debug build runs fine (the packages are all in the local Nuget cache, but the published output is missing Microsoft.Management.Infrastructure.dll and it fails to execute.
My publish command is:
dotnet^
publish^
ConsoleApp1.csproj^
--self-contained^
--configuration Release^
--runtime win-x64^
--output pub
Does anyone know what I am doing incorrectly? According to Choosing the right PowerShell NuGet package for your .NET project, I am using the correct NuGet reference.