Functions/Get-BsgPbiReportConnection.ps1

<#
    .SYNOPSIS
        Get Power BI report connection information of a .pbix file.
         
    .DESCRIPTION
        Get the connection information of a Power BI report file (.pbix) as a PSCustomObject.
        The connection information of a report can be accessed after renaming a .pbix file to a .zip file.
 
    .PARAMETER Filename
        The filename of the PBI report file (.pbix).
 
    .PARAMETER Path
        The path to the folder where the .pbix file is stored.
 
    .EXAMPLE
        # Get report connection
        Get-BsgPbiReportConnection -Filename "Excel_Simple_Retail_UsingExistingPBIDataset_c1f63ad0-9324-476a-ab46-1df8af9ca81b" -Path "C:\temp\BSG PBI Administration\Backup\Workspaces\BSGroup DA - Test Workspace\Reports"
         
    .INPUTS
 
    .OUTPUTS
        Returns a PSCustomObject with the connection information of the PBIX file.
    .NOTES
#>

function Get-BsgPbiReportConnection{

    param (
        [Parameter(Mandatory=$true)][string]$Filename,
        [Parameter(Mandatory=$true)][string]$Path
    )

    try{

        # Define path
        $Path_Report = Join-Path -Path $Path -ChildPath $Filename

        # Check if file exists
        if((Test-Path "$Path_Report.pbix") -eq $false){
            Throw "File `"$Path_Report.pbix`" does not exist."
        }

        # Change filetype to .zip
        Rename-Item -Path "$Path_Report.pbix" -NewName "$Filename.zip" -ErrorAction Stop

        # Open connection file from .zip archive
        $zip = [System.IO.Compression.ZipFile]::Open("$Path_Report.zip", "Read")
        $ConnectionFile = $zip.Entries | where-object { $_.Name -eq "Connections"}

        # Read connection file into string
        $stream = $ConnectionFile.Open()
        $reader = New-Object IO.StreamReader($stream)
        $ConnectionString = $reader.ReadToEnd()

        # close everything
        $reader.Close()
        $stream.Close()
        $zip.Dispose()

        # Change filetype back to .pbix
        Rename-Item -Path "$Path_Report.zip" -NewName "$Filename.pbix"

        return [PSCustomObject]$ConnectionString | ConvertFrom-Json

    } catch{
        throw "Error trying to get report connection information for file `"$Filename.pbix`"." + "`n" + $_
    }

}