问题
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