title: How to pass a COM object parameter to a PowerShell function?
body: <p>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 <code>Excel.Application</code> COM object for every spreadsheet, I'd like to pass an instance to the function, so that the instance can be reused.</p>
  
  <p>Here's my function:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>When I try to run the function, I get an error:</p>
  
  <pre><code>You cannot call a method on a null-valued expression.
  At T:\rclocher3\Excel-to-PDF2.ps1:32 char:35
  +     $WorkBook = $xl.Workbooks.Open &lt;&lt;&lt;&lt; ($filename)
      + CategoryInfo          : InvalidOperation: (Open:String) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull
  </code></pre>
  
  <p>How do I pass an instance of the COM object <code>Excel.Application</code> to a PowerShell function?</p>