【问题标题】:Can't load a .NET type in PowerShell无法在 PowerShell 中加载 .NET 类型
【发布时间】:2012-05-24 14:10:55
【问题描述】:

这是一个奇怪的问题。我正在尝试加载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

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

【问题讨论】:

    标签: reflection powershell assemblies


    【解决方案1】:

    你的new-object 语法有点不对劲。试试这个:

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

    【讨论】:

    • 是的,在 PowerShell 中使用 C# 样式的“构造函数”在技术上是无效的。按预期方式在 New-Object cmdlet 上使用 -TypeName 和 -ArgumentList 参数。
    【解决方案2】:

    无需加载任何内容。使用 adsi 类型加速器:

    [adsi]"WinNT://localhost,computer"
    

    【讨论】:

    • 有什么好的文档吗?事情似乎不是很“可发现”
    • 搜索powershell类型的加速器
    【解决方案3】:

    我认为New-Object 的语法不正确。取自 [一些关于 New-Object 的文档]:1

    New-Object System.DirectoryServices.DirectoryEntry("WinNT://localhost,computer")
    

    【讨论】:

      猜你喜欢
      • 2015-10-11
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      相关资源
      最近更新 更多