使PowerShell等待Excel完成刷新数据透视表

所以我开发了一个PowerShell脚本来刷新大约40个大的Excel文件并保存它们,在这个脚本中,我运行一个Excelmacros来传递Excel(ODBC)连接参数,然后在刷新完成后从Excel文件中删除它们。 我唯一的问题是(对于这40个文件中的5个文件),当RefreshAll命令启动时,powershell不会等待Excel完成刷新,并传递给下一个命令,该命令是使连接无效的macros,从而导致错误macros中的“1004”(在文件仍在刷新时无法访问Excel连接)

经过一番研究,我知道在PowerShell v2中有后台作业的概念,但在我的情况下,这不是一个旁路过程,它属于Excel进程,所以我的PowerShell不必等待Excel退出继续执行,相反,我需要excel保持打开才能继续执行powershell。

我也知道,开始 – hibernate命令对于我的情况并不是最好的,因为没有固定的刷新时间值,每个文件都有它的时间,并且每个月份的每个周期都有它的时间(数据量每天增加,直到月底结束)

所以我的问题是:是否有可能使PowerShell的testing,如果Excel文件已经完成其数据刷新,如果是的话,它会继续,否则它会等待更多?

任何帮助将不胜感激,并提前感谢您。 PS:请原谅我的一年级英语:)。

霰弹枪的做法:

  1. Excel具有Application.Ready属性。 它应该表明什么时候Excel准备进行自动化通信,但细节不清楚 。 尝试这样的事情:

    $Excel = New-Object -ComObject Excel.Application # Do your stuff here # Wait for Excel to became ready while (!$Excel.Ready) { Start-Sleep -Seconds 1 } # Do other stuff 
  2. QueryTable具有刷新属性。 尝试这个:

     $Excel = New-Object -ComObject Excel.Application $Workbook = $Excel.Workbooks.Open('C:\Path\To\Workbook\Data.xlsx') # Are any of the QueryTables refreshing? # Don't have Excel right now, so expression below might need some tweaking While (($Workbook.Sheets | ForEach-Object {$_.QueryTables | ForEach-Object {if($_.QueryTable.Refreshing){$true}}})) { Start-Sleep -Seconds 1 } 
  3. ODBCConnection有刷新属性。试试这个:

     $Excel = New-Object -ComObject Excel.Application $Workbook = $Excel.Workbooks.Open('C:\Path\To\Workbook\Data.xlsx') # Is ODBCConnection refreshing? # Don't have Excel right now, so expression below might need some tweaking While ($Workbook.ODBCConnection.Refreshing) { Start-Sleep -Seconds 1 } 
  4. 也许这5个文件有PivotCache.BackgroundQuery , ODBCConnection.BackgroundQuery或QueryTable.BackgroundQuery属性设置为true?