PowerShell and COM objects.
While developing a COM object for scripting use I wanted to provide a VBScript sample as well as a PowerShell sample.
While creating the PowerShell sample I received an unexpected error message when setting a property value. Some quick review shows that PowerShell 1.0 (I did not check with the 2.0 CTP yet) cannot handle write-only COM properties.
Consider the following PowerShell script:
$obj = New-Object -comObject “PropertyTest.PropTest”
$obj.ReadWrite = “Some text”
$readonly = $obj.ReadOnly
$obj.WriteOnly = “some more text”
The object’s properties behave as they are named. If you run these instructions one by one in PowerShell you get theĀ following error message:
Exception setting “WriteOnly”: “Type mismatch. (Exception from HRESULT: 0×80020
005 (DISP_E_TYPEMISMATCH))”
At line:1 char:6
+ $obj.W <<<< riteOnly = “some more text”
Read-write and read-only properties work fine, only write-only properties are affected. I have uploaded the test component here: PropertyTest.dll
Obviously you need to run regsvr32 PropertyTest.dll if you want to test this.
Tags: com, powershell, scripting








August 7th, 2008 at 12:35 am
I registered the dll and run the code without the writeOnly call, it seems that none of the properties gets updated:
PS > $obj = New-Object -comObject “PropertyTest.PropTest”
PS > $obj.ReadWrite = “Some text”
PS > $obj.ReadWrite
# no output
PS > $readonly = $obj.ReadOnly
PS > $readonly
# no output
PS > $obj
ReadWrite ReadOnly WriteOnly
——— ——– ———
-Shay
August 7th, 2008 at 1:30 am
The object doesn’t really do anything. It’s just there to illustrate the error PowerShell spits out. I can add the source for the component if there is interest.
August 7th, 2008 at 3:00 am
Ya, PowerShell COM interoperability is not that good, and that’s an under statment :), BTW, I can ’set’ the WriteOnly member this way:
$obj.gettype().InvokeMember(”WriteOnly”,”SetProperty”,$null,$obj,”some text”)
August 7th, 2008 at 3:45 am
Same error on XP SP2 with v2 CTP2.
I’d like to see the source.
August 7th, 2008 at 9:16 am
You can download it at
ftp://ftp.sapien.com/propertytest.zip
August 7th, 2008 at 6:56 pm
Bruce Payette admits their COM support is lacking in his book.
August 7th, 2008 at 8:35 pm
I didn’t want to point any fingers, I just think it’s important to know what exactly happens, specially since the error message does not provide any relevant information.
A non-programmer could get quite frustrated with this
August 8th, 2008 at 1:05 pm
Yes, PowerShell does lack a bit on the COM side. Ugly workaround, call VBScript to call the COM object. The built-in disk quota COM object suffers here also when called from PowerShell directly.
I’ve also have similar problems with a COM object from HP for their OpenView Operations agent.
Is COM dead?
August 8th, 2008 at 3:30 pm
It will be as soon as can call CmdLets directly from VBScript or there is a “WScript.LoadAssembly”