Using PowerShell and System.DirectoryServices
, I've been given an object that looks like this:
TypeName: System.__ComObject
Name MemberType Definition
---- ---------- ----------
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
ToString Method string ToString()
All example code that I can find deals with creating new COM objects from PowerShell, not wrapping existing objects that have been returned. How can I usefully deal with this object (enumerate and use the actual properties and methods)?
Note: this object actually does have a type library ("ActiveDs"), but for some reason I am unable to use it out of the box, as a different question (Loading a Type Library via PowerShell and scripting Windows Live Writer) suggests should be the case.
Here is a one-liner showing how to get such an object:
((new-object DirectoryServices.DirectoryEntry -a '
LDAP://somedc').Properties.GetEnumerator() |?{$_.PropertyName -eq 'usnChanged' }).Value[0] | Get-Member
Just a little different approach then Bill Stewart’s:
The idea is that usually you do not need/want to create multiple instances of the ComObject:
If it concerns a method, you need to add the
–Method
switch, in the case of a property, the cmdlet will automatically determine whether the property need to be get or set depending on whether a value is supplied. With this cmdlet you do not require the to create the ComObject first and retrieve e.g. to get theComputerName
(DN) fromADSystemInfo
in a simple oneliner:To do a the same with the
PathName
:A name
NameTranslate
example:Or if you do want to have multiple instances you can first create the ComObject instance and then supply it to the
ComInvoke
function:For the latest
Invoke-ComObject
version, see: https://powersnippets.com/invoke-comobject/PowerShell reflection doesn't properly "see" these objects' properties and methods. To get to the properties and methods, I use some wrapper functions. Here is an example:
Note that the Set-Property and Invoke-Method use an array as their final parameter, so I use @( ) when calling those functions.