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