functions/Watch-PbixFile.ps1

# <copyright file="Watch-PbixFile.ps1" company="Endjin Limited">
# Copyright (c) Endjin Limited. All rights reserved.
# </copyright>

<#
.SYNOPSIS
    A helper for running the Power BI Tools extract command in 'watch' mode.
.DESCRIPTION
    Looks up the Power BI Desktop process ID information before running the required 'pbi-tools.exe' command.
.EXAMPLE
    PS C:\> Watch-PbixFile -PbixFilePath myReport.pbix -ExtractPath src/myReport
    When run in the root of a git repository, generates the required pr-autoflow artefacts under the '.github' folder.
.PARAMETER PbixFilePath
    Path to the source PBIX file being edited in Power BI Desktop.
.PARAMETER ExtractPath
    Path to the folder where the PBIX file will be extracted to.
.PARAMETER PbiDesktopPid
    Allows the the Power BI Desktop process ID to be set manually.
.PARAMETER PbiToolsPath
    Path to the Power BI Tools Windows CLI tool (i.e 'pbi-tools.exe'). When not specified it is assumed to be in your PATH.
#>


function Watch-PbixFile {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string] $PbixFilePath,

        [Parameter(Mandatory=$true)]
        [string] $ExtractPath,

        [Parameter()]
        [int] $PbiDesktopPid,

        [Parameter()]
        [string] $PbiToolsPath = "pbi-tools.exe"
    )

    if (!$IsWindows) {
        Write-Error "The PBI Tools 'extract' functionality is only supported on Windows."
        return
    }

    try {
        $resolvePbixFilePath = Resolve-Path $PbixFilePath
    }
    catch {
        Write-Error "PBIX file not found: $resolvePbixFilePath"
        return
    }

    if (!(Get-Command $PbiToolsPath)) {
        Write-Error "The PBI Tools CLI could be found as an executable command: $PbiToolsPath"
        return
    }

    if (!$PbiDesktopPid) {
        Write-Host "Looking-up process ID for Power BI Desktop session..." -f Yellow
        $pbiInfo = & $PbiToolsPath info | ConvertFrom-Json -Depth 10
        $PbiDesktopPid = $pbiInfo.pbiSessions |
                            ? { $_.PbixPath -eq $resolvePbixFilePath } |
                            Select-Object -ExpandProperty ProcessId
    }

    if (!$PbiDesktopPid) {
        Write-Error "Unable to find an active Power BI Desktop session for the report: $resolvePbixFilePath"
        return
    }

    & $PbiToolsPath extract $resolvePbixFilePath -extractFolder $ExtractPath -pid $PbiDesktopPid -watch
}