Wednesday, September 13, 2023

Extract SQL query from Open Database connection in EXCEL

----
1. This script opens an Excel file, loops through each connection in the workbook, checks if the connection is an OLEDB connection,
2. then prints the command text (SQL query) of each OLEDB connection.
3. Rplace "C:\path\to\your\Spreadshee.xlsx" with the path to your Excel file1.

```sh
# Create an Excel COM object
$excel = New-Object -ComObject Excel.Application
Extracting SQL queries from Excel’s open data connection

# Open the workbook
$workbook = $excel.Workbooks.Open("C:\path\to\your\Spreadshee.xlsx")

# Loop through each connection in the workbook
foreach ($connection in $workbook.connections) {
    # Check if the connection is an OLEDB connection
    if ($connection.Type -eq 2) {
        # Get the OLEDB connection
        $oledbConnection = $connection.OLEDBConnection

        # Print the command text (SQL query)
        Write-Output $oledbConnection.CommandText
    }
}

# Close the workbook and quit Excel
$workbook.Close()
$excel.Quit()

# Release the COM objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

```
Please note that this script requires Excel to be installed on your machine, as it uses Excel’s COM object model.
Also, running scripts that use COM objects might have issues with non-interactive sessions (like a scheduled task or a remote session).

No comments:

Post a Comment