Windows 11 24H2中.NET 4.7.2调用PowerShell脚本触发类型初始化异常
在.NET 4.7.2环境下运行调用PowerShell的C#代码,普通Windows 11机器上执行正常,但在Windows 11 24H2版本中执行Get-AppxPackage脚本时出现错误(未触发try/catch捕获的异常,仅通过PowerShell错误流返回信息)。执行Write-Output 'Hello from PowerShell!'这类简单脚本无异常。已引用GAC路径下的System.Management.Automation.dll。
执行代码
static void Main(string[] args) { try { string script = "Get-AppxPackage"; using (PowerShell ps = PowerShell.Create()) { ps.AddScript(script); var results = ps.Invoke(); // 输出结果 foreach (var result in results) { Console.WriteLine(result); } // 检查错误 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: The type initializer for '' threw an exception.
详细异常信息(新增日志后)
添加以下日志代码:
Console.WriteLine("Exception: " + error.Exception); Console.WriteLine("InnerException: " + error.Exception.InnerException);
得到详细异常:
Exception: System.TypeInitializationException: 类型初始值设定项引发异常。 --- System.TypeInitializationException: 'WinRT.Projections' 的类型初始值设定项引发异常。 --- System.IO.FileNotFoundException: 未能加载文件或程序集“System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或它的某一个依赖项。系统找不到指定的文件。
在 WinRT.Projections..cctor()
--- 内部异常堆栈跟踪的结尾 ---
在 WinRT.Projections.RegisterAbiDelegate(Type[] delegateSignature, Type delegateType)
在 WinRT.AbiDelegatesInitializer.InitalizeAbiDelegates()
在 .cctor()
--- 内部异常堆栈跟踪的结尾 ---
在 System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(IRuntimeMethodInfo method)
在 System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType, Object target)
在 System.Linq.Expressions.Compiler.LambdaCompiler.CreateDelegate()
在 System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator)
在 System.Management.Automation.CommandProcessor.<>c.b__20_0(Type t)
在 System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
在 System.Management.Automation.CommandProcessor.ConstructInstance(Type type)
在 System.Management.Automation.CommandProcessor.Init(CmdletInfo cmdletInformation)InnerException: System.TypeInitializationException: 'WinRT.Projections' 的类型初始值设定项引发异常。 --- System.IO.FileNotFoundException: 未能加载文件或程序集“System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或它的某一个依赖项。系统找不到指定的文件。
在 WinRT.Projections..cctor()
--- 内部异常堆栈跟踪的结尾 ---
在 WinRT.Projections.RegisterAbiDelegate(Type[] delegateSignature, Type delegateType)
在 WinRT.AbiDelegatesInitializer.InitalizeAbiDelegates()
在 .cctor()
该问题源于Windows 11 24H2中Get-AppxPackage依赖的WinRT组件需要特定版本的System.Numerics.Vectors程序集,而.NET 4.7.2默认未包含此版本,导致加载失败。可通过以下方式解决:
添加程序集绑定重定向:在项目的
App.config中添加重定向配置,将请求的4.1.4.0版本指向系统已兼容的版本(如4.1.3.0或更高):<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.3.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>直接引用对应程序集:通过NuGet安装
System.Numerics.Vectors包(版本4.1.4.0或兼容版本),确保程序集被复制到输出目录,运行时即可找到文件。切换到PowerShell 7:PowerShell 7基于.NET Core/.NET 5+构建,对Windows 11 24H2兼容性更好,可避免.NET Framework版本依赖问题。修改代码指定使用PowerShell 7运行时:
using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("pwsh.exe").AddArgument("-Command").AddArgument("Get-AppxPackage"); var results = ps.Invoke(); // 后续处理逻辑 }
内容的提问来源于stack exchange,提问作者viveknuna

