最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - The type initializer for '<Module>' threw an exception exception in Windows 11 24H2 machine -

programmeradmin0浏览0评论

I am running the powershell script in 4.7.2. Its working fine on windows 11 machines, but its giving an error in windows 11 24H2 machine (not the exception).

static void Main(string[] args)
{
    try
    {
        string script = "Get-AppxPackage";
        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddScript(script);

            var results = ps.Invoke();

            // Display output
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }

            // Check for errors
            if (ps.Streams.Error.Count > 0)
            {
                foreach (var error in ps.Streams.Error)
                {
                    Console.WriteLine("Error: " + error);
                }
            }
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("Exception: " + ex.ToString());
    }
}

Error Details:

Error: The type initializer for '' threw an exception.

I have tried running other Powershell scripts like Write-Output 'Hello from PowerShell! and they are running as expected.

I have referred the System.Management.Automation dll from GAC C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll

I have added the below lines to the code which prints the below logs.

Console.WriteLine("Exception: " + error.Exception);
Console.WriteLine("InnerException: " + error.Exception.InnerException);

Exception: System.TypeInitializationException: The type initializer for '' threw an exception. ---> System.TypeInitializationException: The type initializer for 'WinRT.Projections' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. at WinRT.Projections.tor() --- End of inner exception stack trace --- at WinRT.Projections.RegisterAbiDelegate(Type[] delegateSignature, Type delegateType) at WinRT.AbiDelegatesInitializer.InitalizeAbiDelegates() at tor()
--- End of inner exception stack trace --- at System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IRuntimeMethodInfo method) at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType, Object target) at System.Linq.Expressions.Compiler.LambdaCompiler.CreateDelegate() at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator) at System.Management.Automation.CommandProcessor.<>c.b__20_0(Type t) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at System.Management.Automation.CommandProcessor.ConstructInstance(Type type) at System.Management.Automation.CommandProcessor.Init(CmdletInfo cmdletInformation)

InnerException: System.TypeInitializationException: The type initializer for 'WinRT.Projections' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. at WinRT.Projections.tor() --- End of inner exception stack trace --- at WinRT.Projections.RegisterAbiDelegate(Type[] delegateSignature, Type delegateType) at WinRT.AbiDelegatesInitializer.InitalizeAbiDelegates() at tor()

I am running the powershell script in 4.7.2. Its working fine on windows 11 machines, but its giving an error in windows 11 24H2 machine (not the exception).

static void Main(string[] args)
{
    try
    {
        string script = "Get-AppxPackage";
        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddScript(script);

            var results = ps.Invoke();

            // Display output
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }

            // Check for errors
            if (ps.Streams.Error.Count > 0)
            {
                foreach (var error in ps.Streams.Error)
                {
                    Console.WriteLine("Error: " + error);
                }
            }
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine("Exception: " + ex.ToString());
    }
}

Error Details:

Error: The type initializer for '' threw an exception.

I have tried running other Powershell scripts like Write-Output 'Hello from PowerShell! and they are running as expected.

I have referred the System.Management.Automation dll from GAC C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll

I have added the below lines to the code which prints the below logs.

Console.WriteLine("Exception: " + error.Exception);
Console.WriteLine("InnerException: " + error.Exception.InnerException);

Exception: System.TypeInitializationException: The type initializer for '' threw an exception. ---> System.TypeInitializationException: The type initializer for 'WinRT.Projections' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. at WinRT.Projections.tor() --- End of inner exception stack trace --- at WinRT.Projections.RegisterAbiDelegate(Type[] delegateSignature, Type delegateType) at WinRT.AbiDelegatesInitializer.InitalizeAbiDelegates() at tor()
--- End of inner exception stack trace --- at System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IRuntimeMethodInfo method) at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType, Object target) at System.Linq.Expressions.Compiler.LambdaCompiler.CreateDelegate() at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator) at System.Management.Automation.CommandProcessor.<>c.b__20_0(Type t) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at System.Management.Automation.CommandProcessor.ConstructInstance(Type type) at System.Management.Automation.CommandProcessor.Init(CmdletInfo cmdletInformation)

InnerException: System.TypeInitializationException: The type initializer for 'WinRT.Projections' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. at WinRT.Projections.tor() --- End of inner exception stack trace --- at WinRT.Projections.RegisterAbiDelegate(Type[] delegateSignature, Type delegateType) at WinRT.AbiDelegatesInitializer.InitalizeAbiDelegates() at tor()

Share Improve this question edited Mar 14 at 12:13 Santiago Squarzon 62k5 gold badges24 silver badges54 bronze badges asked Mar 13 at 11:03 viveknunaviveknuna 12 bronze badges 6
  • @Charlieface it's not throwing exceptions, its giving an error – viveknuna Commented Mar 13 at 13:15
  • Console.WriteLine("Error: " + error.Exception); Console.WriteLine("Error: " + error.Exception.InnerException); – Charlieface Commented Mar 13 at 13:44
  • Just to confirm, in your csproj, you're using <TargetFrameworks>net472</TargetFrameworks> and <PackageReference Include="PowerShellStandard.Library" Version="5.1.1" /> ? If so, this code should work correctly – Santiago Squarzon Commented Mar 13 at 14:13
  • @Charlieface I have added the exception and inner exception , please check the question – viveknuna Commented Mar 13 at 14:22
  • @SantiagoSquarzon just FYI <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>, but not using PowerShellStandard. I have mentioned in my question. I am using System.Management.Automation from the GAC – viveknuna Commented Mar 13 at 14:41
 |  Show 1 more comment

1 Answer 1

Reset to default 0

The issue is that the assemblies used by the Appx Module aren't included in the GAC, instead they're shipped with PowerShell 5.1 in Windows 11.

So there are a few workarounds, the one I'd recommend is to install those assemblies in the GAC following the approach from jborean93's gist, then your console app should run properly.

$publish = [System.EnterpriseServices.Internal.Publish]::new()

@(
    'System.Numerics.Vectors.dll',
    'System.Runtime.CompilerServices.Unsafe.dll',
    'System.Security.Principal.Windows.dll',
    'System.Memory.dll'
) | ForEach-Object {
    $dllPath = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\$_"
    $publish.GacInstall($dllPath)
}

Alternatively, if you don't want to install the assemblies, you could manually reference them in your .csproj. You should be able to locate them in the same folder as PowerShell 5.1 itself. You could also copy-paste them to your project and reference them from there.

  <ItemGroup>
    <PackageReference Include="PowerShellStandard.Library" Version="5.1.1" />
    <Reference Include="C:\Windows\System32\WindowsPowerShell\v1.0\System.Numerics.Vectors.dll" />
    <Reference Include="....." />
    <!-- Rest of required assemblies here -->
  <ItemGroup>

Yet another option, which might work, is to load these assemblies in the PowerShell instance itself, this would just require a code change:

try
{
    using (PowerShell ps = PowerShell.Create())
    {
        var results = ps
            .AddCommand("Add-Type")
            .AddParameter(
                parameterName: "Path",
                value: @"C:\Windows\System32\WindowsPowerShell\v1.0\System.*.dll")
            .AddStatement()
            .AddCommand("Get-AppxPackage")
            .Invoke();

        // Display output
        foreach (var result in results)
        {
            Console.WriteLine(result);
        }

        // Check for errors
        if (ps.Streams.Error.Count > 0)
        {
            foreach (var error in ps.Streams.Error)
            {
                Console.WriteLine("Error: " + error);
            }
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine("Exception: " + ex.ToString());
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论