functions/Get-Workspace.ps1


<#
.SYNOPSIS
Returns Power BI Workspace info.
 
.DESCRIPTION
This command returns the Workspace information for all Workspaces or for a specific workspace if the workspaceName parameter is
provided. This command is used within other commands to retrieve Workspace ID where a Workspace Name is provided.
 
.PARAMETER authToken
This is the required API authentication token (string) generated by the Get-PBIAuthTokenUnattended or Get-PBIAuthTokenPrompt commands.
 
.PARAMETER workspaceName
Optional parameter to restrict data to a specific Workspace Name. The Workspace ID is retrieved using this name by the function
 
.EXAMPLE
Get-Workspace -authToken $auth
Get-Workspace -authToken $auth -workspaceName 'Workspace Name'
 
.NOTES
General notes
#>

function Get-Workspace{

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]
        $authToken,
        
        [string]
        $workspaceName
    )

    Begin{

        Write-Verbose 'Building Rest API header with authorization token'
        $authHeader = @{
            'Content-Type'='application/json'
            'Authorization'='Bearer ' + $authToken
        }
    }
    Process{

        try {
            
            if($workspaceName){
                Write-Verbose 'Workspace Name provided. Fetching all Workspaces'
                $uri = "https://api.powerbi.com/v1.0/myorg/groups"
                $workspace = Invoke-RestMethod -Uri $uri -Headers $authHeader -Method GET

                Write-Verbose 'Matching Workspace Name to ID'
                $workspaces = $workspace.value | Where-Object{$_.name -eq $workspaceName}
            }
            else{
                $uri = "https://api.powerbi.com/v1.0/myorg/groups"
            
                $workspace = Invoke-RestMethod -Uri $uri -Headers $authHeader -Method GET
                $workspaces = $workspace.value
            }
        }
        catch {
            throw "Error retrieving Workspaces from API: $($_.Exception.Message)"
        }
        
    }
    End{    
        Write-Verbose 'Returning Workspace info'
        return $workspaces

    }
}