How can I catch an Excel file's macro error in Powershell?

懵懂的女人 提交于 2020-12-12 04:40:50

问题


I have a scheduled PowerShell script that opens Excel, opens a file and runs a macro. If an error arises, I need to display it in the shell and interrupt the script. (I can not afford the script to hang while waiting for user input)

Here is my current script ($excelDataPath is defined earlier in the script)

$Excel = New-Object -ComObject "Excel.Application"
$Excel.DisplayAlerts = $false
$Excel.AskToUpdateLinks = $false
$Excel.Visible = $true

$Workbook = $Excel.Workbooks.Open($excelDataPath)
$Excel.Run("Macro1")
$Workbook.Save()
$Workbook.Close($true)

Thanks


回答1:


I think from the PowerShell point of view, this will catch and display the exception that has occurred:

try {
    $Excel = New-Object -ComObject "Excel.Application"
    $Excel.DisplayAlerts = $false
    $Excel.AskToUpdateLinks = $false
    $Excel.Visible = $true

    $Workbook = $Excel.Workbooks.Open($excelDataPath)
    $Excel.Run("Macro1")
    $Workbook.Save()
    $Workbook.Close($true)
    $Excel.Close()
}
catch {
    $exception = $_.Exception
    while ($exception.InnerException) {
        $exception = $exception.InnerException
    }
    # Throw a terminating error. 
    throw $exception
}
finally {
    # IMPORTANT! Always release the comobjects used from memory when done
    if ($Workbook) { [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Workbook) | Out-Null }
    if ($Excel)    { [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null }
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

However, as for the VBA macro code you did not show us, you will have to check to see what it does wit any errors via VBA On Error Statement. Especially the Err.Raise and Throw statements.



来源:https://stackoverflow.com/questions/53740679/how-can-i-catch-an-excel-files-macro-error-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!