Home > database >  How can a Powershell function specify a ComObject parameter type?
How can a Powershell function specify a ComObject parameter type?

Time:06-18

Let's say that I'm trying to write a Powershell function that prints a result set to an Excel worksheet, like this:

function Write-ToWorksheet {
  param (
    [Parameter( Position = 0, Mandatory = $true )]
    [MyLibrary.MyCustomResultType[]]
    $ResultSet,

    [Parameter( Position = 1, Mandatory = $true )]
    [Excel.Worksheet]
    $Worksheet
  )
  # ... Implementation goes here ...
}

And let's say that I'm calling it in a way something like this:

$excel = New-Object -ComObject Excel.Application
$wb = $excel.Workbooks.Add()

$results = Get-MyResults # Never mind what this does.

Write-ToWorksheet -ResultSet $results -Worksheet $wb.Sheets[ 1 ]

And this code will almost work, except that it chokes on my type specification of [Excel.Worksheet].

I realize that it is not necessary to specify the parameter type, and that the code will work just fine without it, as Named arguments

Whereas calling the function via positional arguments works as expected:

Positional arguments

If positional arguments aren't something you'd like to use, then another alternative would be to drop the parameter type constraint and instead check the type using the Type safety via ValidateScript

  • Related