Mass changing pivot table connection strings in Excel using PowerShell

The Problem

As Business Intelligence consultants after a migration to a brand new server inevitably we get asked by the users: “Do why have to redo all my pivot tables in Excel again? All my workbooks stopped working…”

Well, they can but they don’t need to. Where’s a simple code to replace the part that matters. This will iterate all the Excel files in the folder where the Powershell Script is located and and apply the substitution to all the OLEDBConnections that exist in each file:

param (
    $find = "OLD",
    $replace = "NEW"

Set-Location (split-path -parent $MyInvocation.MyCommand.Definition)

$excelApp = New-Object Microsoft.Office.Interop.Excel.ApplicationClass

# Enum all Excel Files
Get-ChildItem "*.xlsx" | ForEach-Object {
    $workbook = $excelApp.Workbooks.Open($_.FullName)

    # fix all connections in workbook
    foreach ($con in $connections.Connections) {
        if ($con.OLEDBConnection.Connection -match $find) {
            Write-Host "Match found on $($_.FullName) - $($con.OLEDBConnection.Connection)"
            $con.OLEDBConnection.Connection = $con.OLEDBConnection.Connection -replace "$find", "$replace"

    # Refresh all pivots

    # clean objects
# close excel


Once again Powershell came to the rescue and saved my clients a few hours of work replacing manually the connections to the data source.

Have fun!


comments powered by Disqus