Functions/Update-BsgPbiReportConnection.ps1

<#
    .SYNOPSIS
        Update Power BI report connection information of a .pbix file.
         
    .DESCRIPTION
        Update the connection information of a Power BI report file (.pbix).
        The connection information 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.
 
    .PARAMETER ConnectionObject
        The object of the connection file (after renaming the .pbix file to .zip, a connection file can be accessed as JSON-String)
 
    .EXAMPLE
        # Update report connection
        Update-BsgPbiReportConnection -Filename "Excel_Simple_Retail_UsingExistingPBIDataset_c1f63ad0-9324-476a-ab46-1df8af9ca81b" -Path "C:\temp\BSG PBI Administration\Backup\Workspaces\BSGroup DA - Test Workspace\Reports" -ConnectionObject $PbiReportConnection
         
    .INPUTS
 
    .OUTPUTS
 
    .NOTES
#>


function Update-BsgPbiReportConnection(){

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

    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", "Update")
        $ConnectionFile = $zip.Entries | where-object { $_.name -eq "Connections"}

        # Write new object to json string
        $ConnectionString = $ConnectionObject | ConvertTo-Json
        $writer = [System.IO.StreamWriter]($ConnectionFile).Open()
        $writer.BaseStream.SetLength(0)
        $writer.Write($ConnectionString)

        # close everything
        $writer.Flush()
        $writer.Close()
        $zip.Dispose()

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

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

}