2015/09/22

Encounter exceptions sometimes when trying to Open a workbook via PowerShell and Microsoft.Office.Interop.Excel

I completed a simple Powershell scripts in order to open an existing Excel workbook, and update the data.
It works like a charm on some Windows PC, but failed sometimes when running on those PC with heavier loadings

Would encountering the following issues

  • Rejected by the callee
  • "Open" MethodNotFound
Trying some workarounds and found that if inserting "Start-Sleep" for seconds, it will relieve the pain some, but still not 100% avoided and waste some time in idle waiting. I start to seek out the way for polling the status of "application.workbooks". Fortunately, the symptom is observed

  • When Application.Workbooks.count = 1, those issues would be reproduced
  • When Application.Workbooks.count = 0, those issue would disappear
Therefore, we could assume that that Application.Workbooks would be ready when it becomes a collection instead of an object only. Now, we could start polling the Application.Workbooks.Count to test if count becomes 0. When it become 0, we could resume the operations we want.

Sample Code

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$excel.DisplayAlerts = $false
#When the count of $excel.workbooks is 0, $excel.workbooks is ready.
#When the count is greater than 0, $excel.workbooks is not initialized yet
while ($excel.workbooks.count -gt 0) {
Start-Sleep -milliseconds 100
Write-Debug "Initializing..."
}
             
$workbook = $excel.workbooks.Open($file)