By using the windows PowerShell it is possible to access COM Objects. Within this article I want to show you how to create, use and remove a reference to a COM Object.
Creating a COM Object reference
If you want to create a reference to a COM Object you may use the new-object cmdlet and pass the name of the object. Furthermore the parameter -comobject must be used. The following example shows how to create a reference to the COM Object “MyComClass”.
$myObject = new-object -comobject MyCommClass
Remove a COM Object reference
If you don’t need the object reference anymore, you should remove the reference to allow the garbage collector to do the cleanup procedures. To remove the reference you may use the Remove-Variable cmdlet and pass your variable.
Remove-Variable myObject
Execute a COM Object function
If you have created a COM Object you can use the object variable to execute his function. For example if the COM Objects offers a function “DoSomething”, it is possible to use the function with the following command.
$myObject.DoSomething()
If the function “DoSomething” has an input parameter, for example a string parameter, you can pass a value inside the brackets.
$myObject.DoSomething(“value”)
If the function has a return value it may be stored within a new variable:
$result = $myObject.DoSomething(“value”)
Pass a parameter by reference
Sometimes functions have parameters which must be passed by reference. In this case you can create a new variable and use the keyword [ref] to pass the variable. The following example shows the function “DoSomething” with a reference to a string list as function parameter.
$myList = New-Object ‚System.Collections.Generic.List[string]‘
$myObject.DoSomething([ref] $myList)
Summary
The following script code shows a full example how a COM object may be used.
$myObject = new-object -comobject MyCommClass
$myList = New-Object ‚System.Collections.Generic.List[string]‘
$myObject.DoSomething([ref] $myList)
Remove-Variable myObject