Skip to content

The type initializer for 'System.Management.Automation.ExperimentalFeature' threw an exception. #18109

Closed

Description

Prerequisites

Steps to reproduce

I am experiencing a problem when running the PowerShell SDK in a kiosk (AssignedAccess) environment in a WindowsBackgroundService. When I am using the library in a non-kiosk environment it works fine. But the weird thing is that once I am in the kiosk or when I get back from it, I am always getting an exception. I already asked this on StackOverflow but without any solutions.

Expected behavior

$user = "ExamX"
$Sid = (Get-LocalUser -Name $user).SID.Value
Remove-LocalUser -SID $Sid
Clear-AssignedAccess
sc.exe stop "ExamX Service"
sc.exe delete "ExamX Service"
$path = "HKLM:\SOFTWARE\ExamX\ExamInfo\"
Remove-Item -Recurse $path -ErrorAction SilentlyContinue

Actual behavior

Exception Trace 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.AsyncResult.EndInvoke()
   at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
   at ExamX_Service.WindowsService.PowershellHandler.Execute() in C:\ExamX\Service\ExamX_Service\ExamX_Service\PowershellHandler.cs:line 33
   at ExamX_Service.WindowsService.WindowsBackgroundService.RunRecoveryScript(ILogger`1 logger) in C:\ExamX\Service\ExamX_Service\ExamX_Service\WindowsBackgroundService.cs:line 134
   at ExamX_Service.WindowsService.WindowsBackgroundService.ExecuteAsync(CancellationToken stoppingToken) in C:\ExamX\Service\ExamX_Service\ExamX_Service\WindowsBackgroundService.cs:line 110

Error details

No response

Environment data

I can't really execute this command due to the exception being thrown

Visuals

No response

Activity

  1. added
    WG-DevEx-SDKhosting PowerShell as a runtime, PowerShell's APIs, PowerShell Standard, or development of modules
    on Sep 16, 2022
  2. SteveL-MSFT commented on Oct 4, 2022

    @SteveL-MSFT
    Member

    Based on the stacktrace, it seems that somehow this is returning null

    internal static string GetApplicationBase(string shellId)
    {
    // Use the location of SMA.dll as the application base.
    Assembly assembly = typeof(PSObject).Assembly;
    return Path.GetDirectoryName(assembly.Location);
    }
    which should not be the case. You must be hosting PowerShell? Are you building it as a single self-contained exe or something like that such that SMA.dll isn't found?

  3. ProRedMax commented on Oct 5, 2022

    @ProRedMax
    Author

    So I am using a fresh virtual machine (So I am not hosting PowerShell in any way I know) and just calling the PowerShell library. As I mentioned it works fine in a non-kiosk environment. The weird thing is that when I return from the kiosk it still does not work. This is how I am using the library:
    Call in WindowsBackgroundService.cs

            var powershellHandler = new PowershellHandler();
            powershellHandler.AddCommand("Set-ExecutionPolicy Unrestricted");
            foreach (var line in File.ReadAllLines(@"C:\Program Files (x86)\ExamX\ExamX_Service\RecoveryScript.ps1"))
                powershellHandler.AddCommand(line);
    
            return powershellHandler.Execute();

    And this is the actual PowershellHandler:

    public class PowershellHandler
        {
            private readonly PowerShell _powerShell;
    
            public PowershellHandler()
            {
                _powerShell = PowerShell.Create();
            }
    
            public void AddCommand(string command)
            {
                _powerShell.AddScript(command);
            }
    
            public string Execute()
            {
                string errorMsg = string.Empty;
                string output = string.Empty;
                _powerShell.AddCommand("Out-String");
                PSDataCollection<PSObject> outputCollection = new();
                _powerShell.Streams.Error.DataAdded += (object sender, DataAddedEventArgs e) =>
                {
                    errorMsg = ((PSDataCollection<ErrorRecord>) sender)[e.Index].ToString();
                };
    
                IAsyncResult result = _powerShell.BeginInvoke<PSObject, PSObject>(null, outputCollection);
    
                _powerShell.EndInvoke(result);
    
                StringBuilder sb = new();
    
                foreach (var outputitem in outputCollection)
                {
                    sb.AppendLine(outputitem.BaseObject.ToString());
                }
    
                _powerShell.Commands.Clear();
    
                if (!string.IsNullOrEmpty(errorMsg))
                {
                    return errorMsg;
                }
    
                return sb.ToString().Trim();
            }
        }
  4. FeelProud commented on Nov 24, 2022

    @FeelProud

    I would like to support this problem that I have also just encountered.

    Setup :

    • Windows Server 2019

    My application :

    • A Windows Background Service

    Explanation :
    I'm using this following code in my background service

    using System.Collections.ObjectModel;
    using System.Management.Automation;
    using System.ServiceProcess;
    using Microsoft.PowerShell;
    PowerShell.Create().AddCommand("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted")
    PowerShellInstance.Invoke();

    And I'm getting the following error

    System.TypeInitializationException: The type initializer for 
    'System.Management.Automation.Configuration.PowerShellConfig' threw an 
    exception. ---&gt; 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
    
  5. SteveL-MSFT commented on Nov 28, 2022

    @SteveL-MSFT
    Member

    What specific version of the PowerShell SDK are you using?

  6. ghost added
    In-PRIndicates that a PR is out for the issue
    on Nov 28, 2022
  7. ProRedMax commented on Nov 29, 2022

    @ProRedMax
    Author

    I am using 7.2.5

  8. FeelProud commented on Nov 29, 2022

    @FeelProud

    I am using 7.2.7 for my part

  9. tannertaylor commented on Nov 30, 2022

    @tannertaylor

    Just wanted to throw my voice in here as well. I'm getting this exact error with a self-contained single-file app. I'm using version 7.2.4. The PR looks like it ought to fix my problem.

  10. jacknovacloud commented on Dec 14, 2022

    @jacknovacloud

    7.3.0 and getting the same issue with a self contained single file app

  11. ghost removed
    In-PRIndicates that a PR is out for the issue
    on Apr 15, 2023
  12. ghost added
    In-PRIndicates that a PR is out for the issue
    on Apr 27, 2023
  13. ghost removed
    In-PRIndicates that a PR is out for the issue
    on May 27, 2023
  14. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  15. microsoft-github-policy-service commented on Nov 30, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs-TriageThe issue is new and needs to be triaged by a work group.Resolution-No ActivityIssue has had no activity for 6 months or moreWG-DevEx-SDKhosting PowerShell as a runtime, PowerShell's APIs, PowerShell Standard, or development of modules

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions