Search code examples
functionpowershellparameterscom

How to pass a COM object parameter to a PowerShell function?


I have a PowerShell script to open several Excel spreadsheets and write to a cell in each spreadsheet. I'd like to put the code to open each spreadsheet, write to it, and save it in a function. Rather than creating a new instance of the Excel.Application COM object for every spreadsheet, I'd like to pass an instance to the function, so that the instance can be reused.

Here's my function:

function InsertBlurb
{
    param([Object[]]$xl, [string]$filename, [string]$blurb)
    $WorkBook = $xl.Workbooks.Open($filename)
    $WorkSheet = $WorkBook.Sheets.Item("Print Out")
    $WorkSheet.Cells.Item(12, "A") = $blurb
    $WorkBook.Save()
    $WorkBook.Close()
}

# Call looks like this
InsertBlurb($objExcel, $dsBook, $blurb)

When I try to run the function, I get an error:

You cannot call a method on a null-valued expression.
At T:\rclocher3\Excel-to-PDF2.ps1:32 char:35
+     $WorkBook = $xl.Workbooks.Open <<<< ($filename)
    + CategoryInfo          : InvalidOperation: (Open:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

How do I pass an instance of the COM object Excel.Application to a PowerShell function?


Solution

  • First off, your call should be:

    InsertBlurb $objExcel $dsBook $blurb
    

    Powershell functions are called with no parentheses and no commas.

    IDK if you have $xl defined write in the function. Maybe, maybe not...leaning toward the latter, but not sure. You can leave off the type if the type is wrong. Hard to imagine it is an object array.