Search code examples
c#.netpowershellvisual-studioservice

Error with PowerShell Nuget Package in Windows Service


I'm a .net developer working on a windows service and I'm experiencing a problem and was hoping someone could provide help. Detailed below is what we are working with.

  • Windows Service with a .NET 6 Target Framework
  • We're using System.Management.Automation and Microsoft.PowerShell.SDK NuGet packages both on Version 7.2.13 (which are the latest to support .NET 6)
  • This is the line of code: var results = script.Invoke(); with script being a powershell object with our command and params
  • We tried updating to .NET 7 to get the latest .NET Powershell packages but lost access to Windows.Management.Deployment.PackageManager, which we are using for another section of our code base

The error is thrown on script.Invoke. For context, here is the method that calls it:

private void RunPcsScript(string pcsServiceName, string newestVersion, string pcsPath)
        {
            _logger.Info("Creating Powershell");
            using var ps = PowerShell.Create();
            if (!string.IsNullOrEmpty(pcsServiceName))
            {
                _logger.Info("Removing old PCS Service");
                IDictionary removeParams = new Dictionary<String, String>();
                removeParams.Add("Name", pcsServiceName);
                ps.AddCommand("Remove-Service").AddParameters(removeParams).Invoke();
            }
            _logger.Info("Creating new PCS Service");
            IDictionary parameters = new Dictionary<String, String>();
            parameters.Add("BinaryPathName", $"{pcsPath}\\SomeExecutable.exe");
            parameters.Add("DisplayName", "MyServiceName");
            parameters.Add("Name", $"MyServiceName-{newestVersion}");
            var script = ps.AddCommand("New-Service").AddParameters(parameters);
            var results = script.Invoke();
        }
  • This works fine locally but when deploying to another Windows 10 machine, we get this error I have provided a log of the error below
System.TypeInitializationException: The type initializer for 'System.Management.Automation.ExperimentalFeature' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'System.Management.Automation.Configuration.PowerShellConfig' threw an exception.
 ---> System.ArgumentNullException: Value cannot be null. (Parameter 'path1')
   at System.IO.Path.Combine(String path1, String path2)
   at System.Management.Automation.Configuration.PowerShellConfig..ctor()
   at System.Management.Automation.Configuration.PowerShellConfig..cctor()
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExperimentalFeature..cctor()
   --- End of inner exception stack trace ---
   at System.Management.Automation.Runspaces.InitialSessionState.AddVariables(IEnumerable`1 variables)
   at System.Management.Automation.Runspaces.InitialSessionState.CreateDefault()
   at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(PSHost host)
   at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()
   at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
   at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.Invoke(IEnumerable input, PSInvocationSettings settings)
   at System.Management.Automation.PowerShell.Invoke()

Also, if anyone knows what Parameter 'Path1' is, if anyone has any recommendations, I'd love to hear them

Everything listed above and worth noting that we were publishing with the settings

  • release| Any CPU
  • Target Framework net6.0-windows10.0.17763.0
  • Self-contained
  • win-x64 with produce single file being the only option checked for publish options

We expected the same results as were on the local device. Our script executes with no errors.


Solution

  • Sounds like the "Self Contained" is the issue please see: https://github.com/PowerShell/PowerShell/issues/13540