Post

Using COM methods in PowerShell

Overview

PowerShell can create instances of COM objects using New-Object -ComObject. Calling methods on these objects can be difficult though - it doesn’t seem to properly handle methods which have VARIANTs in their signature.

I found this StackOverflow answer which describes the fix. You effectively need to add System.Runtime.InteropServices.VariantWrapper as another level of indirection.

Sample Code

1
2
3
4
5
6
7
$comObject = New-Object -ComObject {...}
$handles = $null
$handleWrapper = New-Object System.Runtime.InteropServices.VariantWrapper $handles

$comObject.MethodCall([ref]$handleWrapper)

# Handles are now available in the $handleWrapper variable.
This post is licensed under CC BY 4.0 by the author.