无法在PowerShell中加载.NET类型

Mic*_*cah 6 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...
Run Code Online (Sandbox Code Playgroud)

它似乎已经加载了程序集,但现在当我尝试实例化一个新对象时它失败了:

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
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试以稍微钝的方式进行,它似乎有效.

$directoryServices = [System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices")
$directoryEntryType = $directoryServices.GetType("System.DirectoryServices.DirectoryEntry")
$machine = New-Object $directoryEntryType("WinNT://localhost,computer")
$machine
Run Code Online (Sandbox Code Playgroud)

它告诉我,我已经成功创建了对象:

distinguishedName :
Path              : WinNT://localhost,computer
Run Code Online (Sandbox Code Playgroud)

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

vcs*_*nes 7

你的new-object语法有点偏.试试这个:

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


Sha*_*evy 5

没有必要加载任何东西.使用adsi类型加速器:

[adsi]"WinNT://localhost,computer"
Run Code Online (Sandbox Code Playgroud)