Unable to load .NET type in PowerShell

This is strange. I am trying to load the System.DirectoryServices assembly and then instantiate the System.DirectoryServices.DirectoryEntry class.

Here is what I am trying to do:

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

It seems that it loaded the assembly correctly, but now when I try to instantiate a new object, it fails:

 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 

However, if I try to make this a bit dumber, it will work.

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

This shows me that I successfully created the object:

 distinguishedName : Path : WinNT://localhost,computer 

What is the right way to do this? What am I doing wrong?

+6
source share
3 answers

The new-object syntax is a bit inactive. Try the following:

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

No need to download anything. Use an accelerator like adsi:

 [adsi]"WinNT://localhost,computer" 
+5
source

I think the syntax of New-Object is incorrect. Adapted from [some New-Object documentation]: 1

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

Source: https://habr.com/ru/post/916569/


All Articles