2012-05-24 23 views
6

To jest dziwne. Próbuję załadować zespół System.DirectoryServices, a następnie utworzyć wystąpienie klasy System.DirectoryServices.DirectoryEntry.Nie można załadować typu .NET w PowerShell

Oto, co usiłuję zrobić:

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... 

Wydaje się, że załadowany grzywny montażową, ale teraz gdy próbuję instancji nowego obiektu nie powiedzie:

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 

jednak , jeśli spróbuję zrobić to w nieco bardziej rozwlekły sposób, wydaje się, że działa.

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

To pokazuje mi, że utworzyliśmy obiekt powodzeniem:

distinguishedName : 
Path    : WinNT://localhost,computer 

Jaki jest właściwy sposób to zrobić? Co ja robię źle?

Odpowiedz

7

Twoja składnia new-object jest trochę wyłączona. Spróbuj:

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

Tak, użycie "konstruktora" stylu C# jest technicznie nieważne w PowerShell. Użyj parametrów -TypeName i -ArgumentList polecenia cmdlet New-Object w sposób, w jaki były przeznaczone. –

0

Myślę, że składnia dla New-Object jest niepoprawna. Zaczerpnięte z [jakiejś dokumentacji New-Object]: 1

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

Nie ma potrzeby, aby załadować wszystko. Użyj akceleratora typu adsi:

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

Czy jest na tym dobra dokumentacja? Rzeczy nie wydają się być bardzo "wykrywalne". – Micah

+0

Wyszukuj akceleratory typu Power Shell –

+0

+1. To jest "właściwa" odpowiedź. – vcsjones

Powiązane problemy