Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't load a .NET type in PowerShell

This is a strange one. I'm trying to load the System.DirectoryServices assembly and then create an instance of the System.DirectoryServices.DirectoryEntry class.

Here's what I'm 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 to have loaded the assembly fine, 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 do it in a slightly more obtuse way, it seems to work.

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

It shows me I've created the object successfully:

distinguishedName :
Path              : WinNT://localhost,computer

What's the proper way to do this? What am I doing wrong?

like image 955
Micah Avatar asked May 24 '12 14:05

Micah


People also ask

Can you use .NET in PowerShell?

In this article There are software components with . NET Framework and COM interfaces that enable you to perform many system administration tasks. Windows PowerShell lets you use these components, so you are not limited to the tasks that can be performed by using cmdlets.

How do I add a type in PowerShell?

Example 3: Add types from an assembly The variable references the PowerShell installation directory where the DLL file is located. The $AccType variable stores an object created with the Add-Type cmdlet. Add-Type uses the AssemblyName parameter to specify the name of the assembly.


1 Answers

Your new-object syntax is a little off. Try this:

[System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices")
$machine = new-object -typeName System.DirectoryServices.DirectoryEntry -argumentList "WinNT://localhost,computer"
like image 67
vcsjones Avatar answered Oct 12 '22 21:10

vcsjones