Skip to content

Getting ArgumentNullException exception on calling System.Management.Automation.PowerShell.Create() when publishing a single file exe #24070

Closed

Description

Prerequisites

Steps to reproduce

  1. Create a dotnet console app.
  2. Add nuget package System.Management.Automation, Microsoft.Powershell.SDK
  3. Write below code in Program.cs of the console application
var shell = PowerShell.Create()
            .AddCommand("Set-ExecutionPolicy")
            .AddParameter("Scope", "Process")
            .AddParameter("ExecutionPolicy", "Unrestricted")
            .AddScript(
                $"Write-Host 'Hello World!'");

        var results = await shell.InvokeAsync();
  1. Run dotnet publish -c Release -o .\bin\Publish --self-contained true --runtime win-x64 /p:PublishSingleFile=true
  2. then `cd .\bin\Publish
  3. run the exe file.
  4. You'll get below error:
 System.ArgumentNullException: Value cannot be null. (Parameter 'path1')
         at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
         at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
         at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
      --- End of stack trace from previous location ---

Expected behavior

should not throw exception.

Actual behavior

Throwing System.ArgumentNullException exception

Error details

No response

Environment data

Name                           Value
----                           -----
PSVersion                      7.4.2
PSEdition                      Core
GitCommitId                    7.4.2
OS                             Microsoft Windows 10.0.22621
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Activity

  1. SteveL-MSFT commented on Jul 22, 2024

    @SteveL-MSFT
    Member

    I believe the problem is that PowerShell uses the location of System.Management.Automation.dll to get the location of $PSHOME which is what fails when built into a single exe. I was working on a change to allow building pwsh as a singleexe (which as other problems), but I can submit a simple change that would (I think) fix your problem.

  2. added
    Issue-BugIssue has been identified as a bug in the product
    and removed
    Needs-TriageThe issue is new and needs to be triaged by a work group.
    on Jul 22, 2024
  3. kasini3000 commented on Jul 22, 2024

    @kasini3000

    #23797
    #13540

    Such a big repair, thank you ! I will tell my father

  4. mySCHOTT commented on Aug 1, 2024

    @mySCHOTT

    Not sure, if https://github.com/PowerShell/PowerShell/pull/24072 fix/solve the issue.

    Steps to reproduce

    1. Get the same issue on a Windows PC, if using the following DLL based on .NET Framework 4.8.1 with PowerShell v5.1 <System.Management.Automation> with .NET v8 SingleFile EXE.

    <Issue.PowerShell_v5 with <System.Management.Automation> v2.0.50727>:

    using System;
    using System.Management.Automation;
    
    namespace Issue.PowerShell_v5
    {
        public class PowerShellExecutor
        {
            public void ExecuteScript(string script)
            {
                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.AddScript(script);
                    var results = powerShell.Invoke();
    
                    foreach (var result in results)
                    {
                        Console.WriteLine(result.ToString());
                    }
                }
            }
        }
    }
    

    And with following <App.config>:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8.1"/>
        </startup>
    </configuration>
    
    1. Then create the .NET v8 EXE referencing the previsous DLL as Assembly.

    <Issue.PowerShell_v7>:

    namespace Issue.PowerShell_v7;
    
    using Issue.PowerShell_v5;
    public class Program
    {
        public static void Main(string[] args)
        {
            //Console.WriteLine("##########################");
            //Console.WriteLine("Reference to .NET 8.0");
            //Console.WriteLine("##########################");
            //PowerShellExecutor executor = new();
            //executor.ExecuteScript("Get-Process");
    
            Console.WriteLine("##########################");
            Console.WriteLine("Reference to .NET Framework 4.8");
            Console.WriteLine("##########################");
            PowerShell_v5.PowerShellExecutor executorV5 = new();
            executorV5.ExecuteScript("Get-Process");
            Console.WriteLine("##########################");
        }
    }
    
    1. As a final step, publish the program as a SingleFile with the following FolderProfile:

    <FolderProfile.pubxml>:

    <?xml version="1.0" encoding="utf-8"?>
    <!--
    https://go.microsoft.com/fwlink/?LinkID=208121.
    -->
    <Project>
      <PropertyGroup>
        <Configuration>Release</Configuration>
        <Platform>x64</Platform>
        <PublishDir>[FolderPlaceholder]\Issue.PowerShell_v7</PublishDir>
        <PublishProtocol>FileSystem</PublishProtocol>
        <_TargetId>Folder</_TargetId>
        <TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <SelfContained>true</SelfContained>
        <PublishSingleFile>true</PublishSingleFile>
        <PublishReadyToRun>false</PublishReadyToRun>
        <PublishTrimmed>false</PublishTrimmed>
      </PropertyGroup>
    </Project>
    
    1. Run the SingleFile EXE, get mentioned errors as well, if using PowerShell v5 too:

    image

    Expected behavior
    PowerShell v5 should run without any exceptions in this case.

    ############################
    20240802: Update (1) , why my exception failed in .NET 8 using PS v5.x:
    image

    Will check my code again- I'm sorry if it's my code.

    ############################
    20240802: Update (2)
    image

    ############################
    20240802: Update (3)
    In my case, using PowerShell v5 within .NET 8 could be work at Windows >=v10 using RunspaceFactory.CreateOutOfProcessRunspace

    using (Runspace runspace = RunspaceFactory.CreateOutOfProcessRunspace(
        new TypeTable(Array.Empty<string>()),
        new PowerShellProcessInstance(new Version(5, 1), null, null, false)
     ))
    .....
    
  5. SteveL-MSFT commented on Aug 19, 2024

    @SteveL-MSFT
    Member

    mySCHOTT there is no intent to support WinPS5.1 with single-exe

  6. microsoft-github-policy-service commented on Aug 19, 2024

    @microsoft-github-policy-service
    Contributor

    📣 Hey Shreyansh Gupta (@kawaiifoxx), how did we do? We would love to hear your feedback with the link below! 🗣️

    🔗 https://aka.ms/PSRepoFeedback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

In-PRIndicates that a PR is out for the issueIssue-BugIssue has been identified as a bug in the product

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions