You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何PowerShell无法找到已加载程序集中的.NET类?

问题描述

从服务获取.NET程序集并转换为byte[],通过反射成功加载程序集,但PowerShell调用[Class1]::Test()时提示无法找到类型[Class1]。已确认:

  • PowerShell使用的CLR版本(4.0.30319.42000)与程序集编译的.NET 4.0版本一致
  • 调用$asse.GetExportedTypes()能正常找到Class1类型

相关代码示例

PowerShell代码

[byte[]]$bytes = # 从服务获取程序集的代码
$asse = [reflection.assembly]::Load($bytes); 
[Class1]::Test()

错误信息

Unable to find type [Class1].
At line:5 char:1
+ [Class1]::Test()
+ ~~~~~~~~
     + CategoryInfo          : InvalidOperation: (Class1:TypeName) [], RuntimeException
     + FullyQualifiedErrorId : TypeNotFound

.NET类定义(C#)

public class Class1
{
   public static void Test()
   {  
      System.Diagnostics.Process.Start("calc.exe");
   }
}

GetExportedTypes()调用结果

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Class1                                   System.Object
解决方案
  • 使用完全限定名调用:如果Class1属于某个命名空间,必须用[命名空间.Class1]::Test()的形式调用;即使类没有显式命名空间,也可以尝试[global::Class1]::Test()(全局命名空间写法)。
  • 通过加载的程序集直接调用:绕过PowerShell的类型解析逻辑,从已加载的程序集实例中获取类型并执行方法:
    # 直接调用静态方法
    $type = $asse.GetType("Class1")
    $type::Test()
    
    # 或者用反射InvokeMember方法
    $type.InvokeMember(
        "Test",
        [System.Reflection.BindingFlags]::Static -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::InvokeMethod,
        $null,
        $null,
        $null
    )
    
  • 将类型导入PowerShell会话:用Add-Type命令把已加载的程序集类型导入当前会话,让PowerShell能识别:
    Add-Type -AssemblyName $asse.FullName
    [Class1]::Test()
    
  • 确认程序集加载上下文:执行AppDomain.CurrentDomain.GetAssemblies() | Where-Object {$_.FullName -eq $asse.FullName},确认程序集确实已加载到当前应用域中。

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:12:39