Calling COM Objects – Technique 5 of 5 (PowerShell)

In a recent series of blog posts, I described how to write a custom COM object using C++ and the ATL wizard in Visual Studio 2005, and then how to call the COM object using classic C++, JavaScript and VBScript, and C#. In this entry I’ll show you how to call the COM object using Windows PowerShell. My COM component is named MyMathLib and contains a class ("coclass") named MyFuncs which in turn holds a single method — Sum(x,y) which just returns the sum (result of addition) of two long ints. Let’s suppose that my COM component project is saved in a root directory arbitrarily named VS223.
PowerShell is Microsoft’s new command shell and scripting language. You can think of PowerShell as a dramatic upgrade to the old cmd.exe shell and .BAT files. PowerShell is currently a separate install and is available for Windows 2000, Windows XP, and Windows Vista. PowerShell will ship as part of the upcoming Windows Server "Longhorn" in a few months. Let’s see how to call MyMathLib interactively. Launch an instance of PowerShell. Issue a "set-location \" command to change the working directory to the system root, then issue a "clear-host" command to clear the screen. (You can also type shortcuts "cd \" and "cls"). Now type:
PS C:\> $obj = new-object -comObject ‘MyMathLib.MyFuncs’
PS C:\> $obj | get-member
PS C:\> $ans = $obj.Sum(4,8)
PS C:\> $ans
The first statement instantiates an object $obj as an instance of the MyFuncs class which is part of the MyMathLib namespace (realized as MyMathLib.dll). PowerShell objects/variables are preceded by the ‘$’ character. The new-object is an intrinsic PowerShell cmdlet ("command-let"). There are about 130 intrinsic cmdlets and they form the heart of PowerShell functionality. The second statement pipes the $obj object to the get-member cmdlet, which will display the available methods in $obj. The third statement calls the Sum() method and assigns to variable (actually an object) $ans. The fourth statement displays the value of $ans (I could have explicitly typed "write-host $ans" too). Using PowerShell to call classic COM components is very clean and very easy. In addition to using PowerShell interactively, I can also write PowerShell scripts to call COM objects. 
This entry was posted in Software Test Automation. Bookmark the permalink.