reflection - 无法在PowerShell中加载.NET类型

标签 reflection powershell assemblies

这是一个奇怪的。我正在尝试加载System.DirectoryServices程序集,然后创建System.DirectoryServices.DirectoryEntry类的实例。

这是我想做的事情:

PS C:> [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices")

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\Windows\assembly\GAC_MSIL\System.DirectoryServices\2.0.0.0__b03f5f7f11d50a3a\System.Directo...

似乎已经很好地加载了程序集,但是现在当我尝试实例化一个新对象时,它失败了:
PS C:\> $computer = new-object [System.DirectoryServices.DirectoryEntry]("WinNT://localhost,computer")
New-Object : Cannot find type [[System.DirectoryServices.DirectoryEntry]]: make sure the assembly containing this type
is loaded.
At line:1 char:23
+ $computer = new-object <<<<  [System.DirectoryServices.DirectoryEntry]("WinNT://localhost,computer")
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

但是,如果我尝试以稍微更钝的方式执行此操作,则它似乎可以工作。
$directoryServices = [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices")
$directoryEntryType = $directoryServices.GetType("System.DirectoryServices.DirectoryEntry")
$machine = New-Object $directoryEntryType("WinNT://localhost,computer")
$machine

它显示了我已经成功创建了对象:
distinguishedName :
Path              : WinNT://localhost,computer

这样做的正确方法是什么?我究竟做错了什么?

最佳答案

您的 new-object 语法有点差。试试这个:

[System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices")
$machine = new-object -typeName System.DirectoryServices.DirectoryEntry -argumentList "WinNT://localhost,computer"

关于reflection - 无法在PowerShell中加载.NET类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739184/

相关文章:

c# - System.Management.Automation 与 .NET Core 3.1 不兼容

arrays - 输出到CSV包含逗号

c# - 程序集是否维护其目录结构?

java - 我应该如何在我的用例中使用 LambdaMetaFactory?

reflection - 路径相关类型与 "underlying types",检查哪些类型?

powershell - 使用安装包时是否跳过确认?

c# - 务实地检测我是否忘记包含程序集

c# - .Net 4.0 中的点程序集引用,似乎无法找到它

java - 我在运行时向方法添加了预定义注释,我希望更改永久有效吗?

c# - 在 C# 中获取对类中某个类型的所有对象的引用