diff --git a/powershell/FabricACEToolkit/FabricACEToolkit.psd1 b/powershell/FabricACEToolkit/FabricACEToolkit.psd1 new file mode 100644 index 0000000..f603b3c --- /dev/null +++ b/powershell/FabricACEToolkit/FabricACEToolkit.psd1 @@ -0,0 +1,215 @@ +# +# Module manifest for module 'FabricACEToolkit' +# +# Generated by: FabricACEToolkit +# +# Generated on: 1/20/2025 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = 'FabricACEToolkit.psm1' + +# Version number of this module. +ModuleVersion = '1.0' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = 'd0110b5c-cfcc-4bcc-8049-468880cf66c8' + +# Author of this module +Author = 'FabricACEToolkit' + +# Company or vendor of this module +CompanyName = 'FabricACEToolkit' + +# Copyright statement for this module +Copyright = '2025 FabricACEToolkit by Tiago Balabuch' + +# Description of the functionality provided by this module +Description = 'FabricACEToolkit' + +# Minimum version of the PowerShell engine required by this module +# PowerShellVersion = '' + +# Name of the PowerShell host required by this module +# PowerShellHostName = '' + +# Minimum version of the PowerShell host required by this module +# PowerShellHostVersion = '' + +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# DotNetFrameworkVersion = '' + +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# ClrVersion = '' + +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' + +# Modules that must be imported into the global environment prior to importing this module +# RequiredModules = @() + +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() + +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() + +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() + +# Format files (.ps1xml) to be loaded when importing this module +# FormatsToProcess = @() + +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +# NestedModules = @() + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Get-FabricCapacity', 'Get-FabricDashboard', 'Get-FabricDataPipeline', + 'New-FabricDataPipeline', 'Remove-FabricDataPipeline', + 'Update-FabricDataPipeline', 'Get-FabricDatamart', + 'Assign-FabricDomainWorkspaceByCapacity', + 'Assign-FabricDomainWorkspaceById', + 'Assign-FabricDomainWorkspaceByPrincipal', + 'Assign-FabricDomainWorkspaceRoleAssignment', 'Get-FabricDomain', + 'Get-FabricDomainWorkspace', 'New-FabricDomain', + 'Remove-FabricDomain', 'Unassign-FabricDomainWorkspace', + 'Unassign-FabricDomainWorkspaceRoleAssignment', + 'Update-FabricDomain', 'Get-FabricEnvironment', + 'Get-FabricEnvironmentLibrary', 'Get-FabricEnvironmentSparkCompute', + 'Get-FabricEnvironmentStagingLibrary', + 'Get-FabricEnvironmentStagingSparkCompute', 'New-FabricEnvironment', + 'Publish-FabricEnvironment', 'Remove-FabricEnvironment', + 'Remove-FabricEnvironmentStagingLibrary', + 'Stop-FabricEnvironmentPublish', 'Update-FabricEnvironment', + 'Update-FabricEnvironmentStagingSparkCompute', + 'Upload-FabricEnvironmentStagingLibrary', 'Get-FabricEventhouse', + 'Get-FabricEventhouseDefinition', 'New-FabricEventhouse', + 'Remove-FabricEventhouse', 'Update-FabricEventhouse', + 'Update-FabricEventhouseDefinition', 'Get-FabricEventstream', + 'Get-FabricEventstreamDefinition', 'New-FabricEventstream', + 'Remove-FabricEventstream', 'Update-FabricEventstream', + 'Update-FabricEventstreamDefinition', 'Get-FabricKQLDashboard', + 'Get-FabricKQLDashboardDefinition', 'New-FabricKQLDashboard', + 'Remove-FabricKQLDashboard', 'Update-FabricKQLDashboard', + 'Update-FabricKQLDashboardDefinition', 'Get-FabricKQLDatabase', + 'Get-FabricKQLDatabaseDefinition', 'New-FabricKQLDatabase', + 'Remove-FabricKQLDatabase', 'Update-FabricKQLDatabase', + 'Update-FabricKQLDatabaseDefinition', 'Get-FabricKQLQueryset', + 'Get-FabricKQLQuerysetDefinition', 'New-FabricKQLQueryset', + 'Remove-FabricKQLQueryset', 'Update-FabricKQLQueryset', + 'Update-FabricKQLQuerysetDefinition', 'Get-FabricLakehouse', + 'Get-FabricLakehouseTable', 'Load-FabricLakehouseTable', + 'New-FabricLakehouse', 'Remove-FabricLakehouse', + 'Start-FabricLakehouseTableMaintenance', 'Update-FabricLakehouse', + 'Get-FabricMirroredDatabase', + 'Get-FabricMirroredDatabaseDefinition', + 'Get-FabricMirroredDatabaseStatus', + 'Get-FabricMirroredDatabaseTableStatus', + 'New-FabricMirroredDatabase', 'Remove-FabricMirroredDatabase', + 'Start-FabricMirroredDatabaseMirroring', + 'Stop-FabricMirroredDatabaseMirroring', + 'Update-FabricMirroredDatabase', + 'Update-FabricMirroredDatabaseDefinition', + 'Get-FabricMirroredWarehouse', 'Get-FabricMLExperiment', + 'New-FabricMLExperiment', 'Remove-FabricMLExperiment', + 'Update-FabricMLExperiment', 'Get-FabricMLModel', 'New-FabricMLModel', + 'Remove-FabricMLModel', 'Update-FabricMLModel', 'Get-FabricNotebook', + 'Get-FabricNotebookDefinition', 'New-FabricNotebook', + 'New-FabricNotebookNEW', 'Remove-FabricNotebook', + 'Update-FabricNotebook', 'Update-FabricNotebookDefinition', + 'Get-FabricPaginatedReport', 'Update-FabricPaginatedReport', + 'Get-FabricReflex', 'Get-FabricReflexDefinition', 'New-FabricReflex', + 'Remove-FabricReflex', 'Update-FabricReflex', + 'Update-FabricReflexDefinition', 'Get-FabricReport', + 'Get-FabricReportDefinition', 'New-FabricReport', + 'Remove-FabricReport', 'Update-FabricReport', + 'Update-FabricReportDefinition', 'Get-FabricSemanticModel', + 'Get-FabricSemanticModelDefinition', 'New-FabricSemanticModel', + 'Remove-FabricSemanticModel', 'Update-FabricSemanticModel', + 'Update-FabricSemanticModelDefinition', 'Get-FabricSparkCustomPool', + 'Get-FabricSparkSettings', 'New-FabricSparkCustomPool', + 'Remove-FabricSparkCustomPool', 'Update-FabricSparkCustomPool', + 'Update-FabricSparkSettings', 'Get-FabricSparkJobDefinition', + 'Get-FabricSparkJobDefinitionDefinition', + 'New-FabricSparkJobDefinition', 'Remove-FabricSparkJobDefinition', + 'Start-FabricSparkJobDefinitionOnDemand', + 'Update-FabricSparkJobDefinition', + 'Update-FabricSparkJobDefinitionDefinition', + 'Get-FabricSQLEndpoint', 'Get-FabricTenantSetting', + 'Get-FabricTenantSettingOverridesCapacity', 'Convert-FromBase64', + 'Convert-ToBase64', 'Get-FabricLongRunningOperation', + 'Get-FabricLongRunningOperationResult', 'Set-FabricApiHeaders', + 'Get-FabricWarehouse', 'New-FabricWarehouse', + 'Remove-FabricWarehouse', 'Update-FabricWarehouse', + 'Add-FabricWorkspaceIdentity', 'Add-FabricWorkspaceRoleAssignment', + 'Assign-FabricWorkspaceCapacity', 'Get-FabricWorkspace', + 'Get-FabricWorkspaceRoleAssignment', 'New-FabricWorkspace', + 'Remove-FabricWorkspace', 'Remove-FabricWorkspaceIdentity', + 'Remove-FabricWorkspaceRoleAssignment', + 'Unassign-FabricWorkspaceCapacity', 'Update-FabricWorkspace', + 'Update-FabricWorkspaceRoleAssignment' + +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() + +# Variables to export from this module +VariablesToExport = 'FabricConfig' + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + # Prerelease string of this module + # Prerelease = '' + + # Flag to indicate whether the module requires explicit user acceptance for install/update/save + # RequireLicenseAcceptance = $false + + # External dependent modules of this module + # ExternalModuleDependencies = @() + + } # End of PSData hashtable + +} # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} + diff --git a/powershell/FabricACEToolkit/FabricACEToolkit.psm1 b/powershell/FabricACEToolkit/FabricACEToolkit.psm1 new file mode 100644 index 0000000..61be6ec --- /dev/null +++ b/powershell/FabricACEToolkit/FabricACEToolkit.psm1 @@ -0,0 +1,65 @@ +$directorySeparator = [System.IO.Path]::DirectorySeparatorChar +$moduleName = $PSScriptRoot.Split($directorySeparator)[-1] +$moduleManifest = $PSScriptRoot + $directorySeparator + $moduleName + '.psd1' +$publicFunctionsPath = $PSScriptRoot + $directorySeparator + 'Public' + $directorySeparator #+ 'ps1' +$privateFunctionsPath = $PSScriptRoot + $directorySeparator + 'Private' + $directorySeparator #+ 'ps1' +$currentManifest = Test-ModuleManifest $moduleManifest + +$aliases = @() +$publicFunctions = Get-ChildItem -Path $publicFunctionsPath -Recurse | Where-Object {$_.Extension -eq '.ps1'} +$privateFunctions = Get-ChildItem -Path $privateFunctionsPath -Recurse | Where-Object {$_.Extension -eq '.ps1'} +$publicFunctions | ForEach-Object { . $_.FullName } +$privateFunctions | ForEach-Object { . $_.FullName } +# Configuration object for module-wide settings + +$FabricConfig = @{ + BaseUrl = "https://api.fabric.microsoft.com/v1" + ResourceUrl = "https://api.fabric.microsoft.com" + FabricHeaders = @{} + TenantIdGlobal = "" + TokenExpiresOn = "" + +} + +Export-ModuleMember -Variable FabricConfig + +$publicFunctions | ForEach-Object { # Export all of the public functions from this module + + # The command has already been sourced in above. Query any defined aliases. + $alias = Get-Alias -Definition $_.BaseName -ErrorAction SilentlyContinue + if ($alias) { + $aliases += $alias + Export-ModuleMember -Function $_.BaseName -Alias $alias + #Export-ModuleMember -Variable FabricConfig, TenantIdGlobal, TokenExpiresOn + } + else { + Export-ModuleMember -Function $_.BaseName + #Export-ModuleMember -Variable FabricConfig, TenantIdGlobal, TokenExpiresOn + } + +} + +$functionsAdded = $publicFunctions | Where-Object {$_.BaseName -notin $currentManifest.ExportedFunctions.Keys} +$functionsRemoved = $currentManifest.ExportedFunctions.Keys | Where-Object {$_ -notin $publicFunctions.BaseName} +$aliasesAdded = $aliases | Where-Object {$_ -notin $currentManifest.ExportedAliases.Keys} +$aliasesRemoved = $currentManifest.ExportedAliases.Keys | Where-Object {$_ -notin $aliases} + +if ($functionsAdded -or $functionsRemoved -or $aliasesAdded -or $aliasesRemoved) { + try { + + $updateModuleManifestParams = @{} + $updateModuleManifestParams.Add('Path', $moduleManifest) + $updateModuleManifestParams.Add('ErrorAction', 'Stop') + if ($aliases.Count -gt 0) { $updateModuleManifestParams.Add('AliasesToExport', $aliases) } + if ($publicFunctions.Count -gt 0) { $updateModuleManifestParams.Add('FunctionsToExport', $publicFunctions.BaseName) } + + Update-ModuleManifest @updateModuleManifestParams + + } + catch { + + $_ | Write-Error + + } + +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Private/Get-FileDefinitionParts.ps1 b/powershell/FabricACEToolkit/Private/Get-FileDefinitionParts.ps1 new file mode 100644 index 0000000..1131e74 --- /dev/null +++ b/powershell/FabricACEToolkit/Private/Get-FileDefinitionParts.ps1 @@ -0,0 +1,57 @@ +function Get-FileDefinitionParts { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$sourceDirectory + ) + try { + if (-Not (Test-Path $sourceDirectory)) { + Write-Message -Message "The specified source directory does not exist: $sourceDirectory" -Level Error + throw + } + + # Get all files from the directory recursively + Write-Message -Message "Get all files from the directory recursively" -Level Debug + $fileList = Get-ChildItem -Path $sourceDirectory -File -Recurse + + # Initialize the output JSON object + $jsonObject = @{ parts = @() } + + # Loop through the files to create parts dynamically + Write-Message -Message "Loop through the files to create parts dynamically" -Level Debug + foreach ($file in $fileList) { + + $relativePath = $file.FullName.Substring($sourceDirectory.Length + 1) -replace "\\", "/" + Write-Message -Message "File found: $relativePath" -Level Debug + Write-Message -Message "Starting encode to base64" -Level Debug + + $base64Content = Convert-ToBase64 -filePath $file.FullName + Write-Message -Message "Adding part to json object" -Level Debug + + $jsonObject.parts += @{ + path = $relativePath + payload = $base64Content + payloadType = "InlineBase64" + } + } + Write-Message -Message "Loop through the files finished" -Level Debug + + return $jsonObject + Write-Message -Message "Parts returned" -Level Debug + } + + catch { + # Step 4: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "An error occurred while getting file definition parts: $errorDetails" -Level Error + throw "An error occurred while encoding to Base64: $_" + } +} + + +# Example usage +#$sourceDirectory = "C:\temp\API\Notebook" +#Get-FileParts -sourceDirectory $sourceDirectory +#$fileParts = Get-FileParts -sourceDirectory $sourceDirectory +#$fileParts | ConvertTo-Json -Depth 10 diff --git a/powershell/FabricACEToolkit/Private/Test-TokenExpired.ps1 b/powershell/FabricACEToolkit/Private/Test-TokenExpired.ps1 new file mode 100644 index 0000000..31ca46e --- /dev/null +++ b/powershell/FabricACEToolkit/Private/Test-TokenExpired.ps1 @@ -0,0 +1,57 @@ +<# +.SYNOPSIS +Checks if the Fabric token is expired and logs appropriate messages. + +.DESCRIPTION +The `Test-TokenExpired` function checks the expiration status of the Fabric token stored in the `$FabricConfig.TokenExpiresOn` variable. +If the token is expired, it logs an error message and provides guidance for refreshing the token. +Otherwise, it logs that the token is still valid. + +.PARAMETER FabricConfig +The configuration object containing the token expiration details. + +.EXAMPLE +Test-TokenExpired -FabricConfig $config + +Checks the token expiration status using the provided `$config` object. + +.NOTES +- Ensure the `FabricConfig` object includes a valid `TokenExpiresOn` property of type `DateTimeOffset`. +- Requires the `Write-Message` function for logging. + +.AUTHOR +Tiago Balabuch +#> +function Test-TokenExpired { + [CmdletBinding()] + param () + + try { + # Ensure required properties have valid values + if ([string]::IsNullOrWhiteSpace($FabricConfig.TenantIdGlobal) -or + [string]::IsNullOrWhiteSpace($FabricConfig.TokenExpiresOn)) { + Write-Message -Message "Token details are missing. Please run 'Set-FabricApiHeaders' to configure them." -Level Error + throw "MissingTokenDetailsException: Token details are missing." + } + + # Convert the TokenExpiresOn value to a DateTime object + $tokenExpiryDate = [datetimeoffset]::Parse($FabricConfig.TokenExpiresOn) + + # Check if the token is expired + if ($tokenExpiryDate -le [datetimeoffset]::Now) { + Write-Message -Message "Your authentication token has expired. Please sign in again to refresh your session." -Level Warning + #throw "TokenExpiredException: Token has expired." + #Set-FabricApiHeaders -tenantId $FabricConfig.TenantIdGlobal + } + + # Log valid token status + Write-Message -Message "Token is still valid. Expiry time: $($tokenExpiryDate.ToString("u"))" -Level Debug + } catch [System.FormatException] { + Write-Message -Message "Invalid 'TokenExpiresOn' format in the FabricConfig object. Ensure it is a valid datetime string." -Level Error + throw "FormatException: Invalid TokenExpiresOn value." + } catch { + # Log unexpected errors with details + Write-Message -Message "An unexpected error occurred: $_" -Level Error + throw $_ + } +} diff --git a/powershell/FabricACEToolkit/Private/Write-Message.ps1 b/powershell/FabricACEToolkit/Private/Write-Message.ps1 new file mode 100644 index 0000000..80da8e1 --- /dev/null +++ b/powershell/FabricACEToolkit/Private/Write-Message.ps1 @@ -0,0 +1,84 @@ +<# +.SYNOPSIS +Logs messages with different severity levels to the console and optionally to a file. + +.DESCRIPTION +The `Write-Message` function provides a unified way to log messages with levels such as Info, Error, Alert, Verbose, and Debug. +It supports logging to the console with color-coded messages and optionally writing logs to a file with timestamps. + +.PARAMETER Message +The message to log. Supports pipeline input. + +.PARAMETER Level +Specifies the log level. Supported values are Info, Error, Alert, Verbose, and Debug. + +.PARAMETER LogFile +(Optional) Specifies a file path to write the log messages to. If not provided, messages are only written to the console. + +.EXAMPLE +Write-Message -Message "This is an info message." -Level Info + +Logs an informational message to the console. + +.EXAMPLE +Write-Message -Message "Logging to file." -Level Info -LogFile "C:\Logs\MyLog.txt" + +Logs an informational message to the console and writes it to a file. + +.EXAMPLE +"Pipeline message" | Write-Message -Level Alert + +Logs a message from the pipeline with an Alert level. + +.NOTES +Author: Tiago Balabuch +#> + +function Write-Message { + [CmdletBinding()] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [string]$Message, + + [Parameter()] + [ValidateSet("Message","Info", "Error", "Warning","Critical", "Verbose", "Debug", IgnoreCase = $true)] + [string]$Level = "Info", + + [Parameter()] + [string]$LogFile + ) + + process { + try { + # Format timestamp + $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + + # Construct log message + $logMessage = "[$timestamp] [$Level] $Message" + + # Write log message to console with colors + switch ($Level) { + "Message" { Write-Host $logMessage -ForegroundColor White } + "Info" { Write-Host $logMessage -ForegroundColor Green } + "Error" { Write-Host $logMessage -ForegroundColor Red } + "Warning" { Write-Host $logMessage -ForegroundColor Yellow } + "Critical" { Write-Host $logMessage -ForegroundColor Red } + "Verbose" { Write-Verbose $logMessage } + "Debug" { Write-Debug $logMessage } + + } + + # Optionally write log message to a file + if ($LogFile) { + try { + Add-Content -Path $LogFile -Value $logMessage -Encoding UTF8 + } catch { + # Catch and log any errors when writing to file + Write-Host "[ERROR] Failed to write to log file '$LogFile': $_" -ForegroundColor Red + } + } + } catch { + Write-Host "[ERROR] An unexpected error occurred: $_" -ForegroundColor Red + } + } +} diff --git a/powershell/FabricACEToolkit/Public/Capacity/Get-FabricCapacity.ps1 b/powershell/FabricACEToolkit/Public/Capacity/Get-FabricCapacity.ps1 new file mode 100644 index 0000000..b1073ea --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Capacity/Get-FabricCapacity.ps1 @@ -0,0 +1,146 @@ + +<# +.SYNOPSIS + Retrieves capacity details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves capacity details from a specified workspace using either the provided capacityId or capacityName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER capacityId + The unique identifier of the capacity to retrieve. This parameter is optional. + +.PARAMETER capacityName + The name of the capacity to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricCapacity -capacityId "capacity-12345" + This example retrieves the capacity details for the capacity with ID "capacity-12345". + +.EXAMPLE + Get-FabricCapacity -capacityName "MyCapacity" + This example retrieves the capacity details for the capacity named "MyCapacity". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Get-FabricCapacity { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$capacityId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$capacityName + ) + try { + # Step 1: Handle ambiguous input + if ($capacityId -and $capacityName) { + Write-Message -Message "Both 'capacityId' and 'capacityName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $capacities = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/capacities" -f $FabricConfig.BaseUrl + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $capacities += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 9: Filter results based on provided parameters + $capacity = if ($capacityId) { + $capacities | Where-Object { $_.Id -eq $capacityId } + } + elseif ($capacityName) { + $capacities | Where-Object { $_.DisplayName -eq $capacityName } + } + else { + # No filter, return all capacities + Write-Message -Message "No filter specified. Returning all capacities." -Level Debug + return $capacities + } + + # Step 10: Handle results + if ($capacity) { + Write-Message -Message "Capacity found matching the specified criteria." -Level Debug + return $capacity + } + else { + Write-Message -Message "No capacity found matching the specified criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve capacity. Error: $errorDetails" -Level Error + return $null + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Dashboard/Get-FabricDashboard.ps1 b/powershell/FabricACEToolkit/Public/Dashboard/Get-FabricDashboard.ps1 new file mode 100644 index 0000000..fc47d95 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Dashboard/Get-FabricDashboard.ps1 @@ -0,0 +1,111 @@ +<# +.SYNOPSIS + Retrieves dashboards from a specified workspace. + +.DESCRIPTION + This function retrieves all dashboards from a specified workspace using the provided WorkspaceId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The ID of the workspace from which to retrieve dashboards. This parameter is mandatory. + +.EXAMPLE + Get-FabricDashboard -WorkspaceId "12345" + This example retrieves all dashboards from the workspace with ID "12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> + +function Get-FabricDashboard { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $Dashboards = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/dashboards" -f $FabricConfig.BaseUrl, $WorkspaceId + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $Dashboards += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 9: Handle results + Write-Message -Message "Returning all Dashboards." -Level Debug + return $Dashboards + + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Dashboard. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Data Pipeline/Get-FabricDataPipeline.ps1 b/powershell/FabricACEToolkit/Public/Data Pipeline/Get-FabricDataPipeline.ps1 new file mode 100644 index 0000000..86a02dc --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Data Pipeline/Get-FabricDataPipeline.ps1 @@ -0,0 +1,155 @@ +<# +.SYNOPSIS + Retrieves data pipelines from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves all data pipelines from a specified workspace using either the provided Data PipelineId or Data PipelineName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Data Pipeline exists. This parameter is mandatory. + +.PARAMETER Data PipelineId + The unique identifier of the Data Pipeline to retrieve. This parameter is optional. + +.PARAMETER Data PipelineName + The name of the Data Pipeline to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricData Pipeline -WorkspaceId "workspace-12345" -Data PipelineId "Data Pipeline-67890" + This example retrieves the Data Pipeline details for the Data Pipeline with ID "Data Pipeline-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricData Pipeline -WorkspaceId "workspace-12345" -Data PipelineName "My Data Pipeline" + This example retrieves the Data Pipeline details for the Data Pipeline named "My Data Pipeline" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Get-FabricDataPipeline { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DataPipelineId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$DataPipelineName + ) + + try { + # Step 1: Handle ambiguous input + if ($DataPipelineId -and $DataPipelineName) { + Write-Message -Message "Both 'DataPipelineId' and 'DataPipelineName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $DataPipelines = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/dataPipelines" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $DataPipelines += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $DataPipeline = if ($DataPipelineId) { + $DataPipelines | Where-Object { $_.Id -eq $DataPipelineId } + } + elseif ($DataPipelineName) { + $DataPipelines | Where-Object { $_.DisplayName -eq $DataPipelineName } + } + else { + # Return all DataPipelines if no filter is provided + Write-Message -Message "No filter provided. Returning all DataPipelines." -Level Debug + $DataPipelines + } + + # Step 9: Handle results + if ($DataPipeline) { + Write-Message -Message "DataPipeline found matching the specified criteria." -Level Debug + return $DataPipeline + } + else { + Write-Message -Message "No DataPipeline found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve DataPipeline. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Data Pipeline/New-FabricDataPipeline.ps1 b/powershell/FabricACEToolkit/Public/Data Pipeline/New-FabricDataPipeline.ps1 new file mode 100644 index 0000000..5314ff8 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Data Pipeline/New-FabricDataPipeline.ps1 @@ -0,0 +1,131 @@ +<# +.SYNOPSIS + Creates a new DataPipeline in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new DataPipeline + in the specified workspace. It supports optional parameters for DataPipeline description + and path definitions for the DataPipeline content. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the DataPipeline will be created. + +.PARAMETER DataPipelineName + The name of the DataPipeline to be created. + +.PARAMETER DataPipelineDescription + An optional description for the DataPipeline. + +.EXAMPLE + New-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineName "New DataPipeline" + This example creates a new DataPipeline named "New DataPipeline" in the workspace with ID "workspace-12345" and uploads the definition file from the specified path. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> + +function New-FabricDataPipeline { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$DataPipelineName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DataPipelineDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/dataPipelines" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $DataPipelineName + } + + if ($DataPipelineDescription) { + $body.description = $DataPipelineDescription + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "DataPipeline '$DataPipelineName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "DataPipeline '$DataPipelineName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId, -location $location + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create DataPipeline. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 b/powershell/FabricACEToolkit/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 new file mode 100644 index 0000000..14adb60 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 @@ -0,0 +1,72 @@ +<# +.SYNOPSIS + Removes a DataPipeline from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove a DataPipeline + from the specified workspace using the provided WorkspaceId and DataPipelineId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the DataPipeline will be removed. + +.PARAMETER DataPipelineId + The unique identifier of the DataPipeline to be removed. + +.EXAMPLE + Remove-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineId "pipeline-67890" + This example removes the DataPipeline with ID "pipeline-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> + +function Remove-FabricDataPipeline { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DataPipelineId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/dataPipelines/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $DataPipelineId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "DataPipeline '$DataPipelineId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete DataPipeline '$DataPipelineId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Data Pipeline/Update-FabricDataPipeline.ps1 b/powershell/FabricACEToolkit/Public/Data Pipeline/Update-FabricDataPipeline.ps1 new file mode 100644 index 0000000..b744a64 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Data Pipeline/Update-FabricDataPipeline.ps1 @@ -0,0 +1,104 @@ +<# +.SYNOPSIS + Updates an existing DataPipeline in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing DataPipeline + in the specified workspace. It supports optional parameters for DataPipeline description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the DataPipeline exists. This parameter is optional. + +.PARAMETER DataPipelineId + The unique identifier of the DataPipeline to be updated. This parameter is mandatory. + +.PARAMETER DataPipelineName + The new name of the DataPipeline. This parameter is mandatory. + +.PARAMETER DataPipelineDescription + An optional new description for the DataPipeline. + +.EXAMPLE + Update-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineId "pipeline-67890" -DataPipelineName "Updated DataPipeline" -DataPipelineDescription "Updated description" + This example updates the DataPipeline with ID "pipeline-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Update-FabricDataPipeline { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DataPipelineId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$DataPipelineName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DataPipelineDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/dataPipelines/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $DataPipelineId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $DataPipelineName + } + + if ($DataPipelineDescription) { + $body.description = $DataPipelineDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "DataPipeline '$DataPipelineName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update DataPipeline. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Datamart/Get-FabricDatamart.ps1 b/powershell/FabricACEToolkit/Public/Datamart/Get-FabricDatamart.ps1 new file mode 100644 index 0000000..09ef401 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Datamart/Get-FabricDatamart.ps1 @@ -0,0 +1,136 @@ +<# +.SYNOPSIS + Retrieves datamarts from a specified workspace. + +.DESCRIPTION + This function retrieves all datamarts from a specified workspace using the provided WorkspaceId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The ID of the workspace from which to retrieve datamarts. This parameter is mandatory. + +.EXAMPLE + Get-FabricDatamart -WorkspaceId "12345" + This example retrieves all datamarts from the workspace with ID "12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Get-FabricDatamart { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$datamartId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$datamartName + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $Datamarts = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all datamarts with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/Datamarts" -f $FabricConfig.BaseUrl, $WorkspaceId + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $Datamarts += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 9: Filter results based on provided parameters + $datamart = if ($datamartId) { + $Datamarts | Where-Object { $_.Id -eq $datamartId } + } + elseif ($datamartName) { + $Datamarts | Where-Object { $_.DisplayName -eq $datamartName } + } + else { + # No filter, return all datamarts + Write-Message -Message "No filter specified. Returning all datamarts." -Level Debug + return $Datamarts + } + + # Step 10: Handle results + if ($datamart) { + Write-Message -Message "Datamart found matching the specified criteria." -Level Debug + return $datamart + } + else { + Write-Message -Message "No Datamart found matching the specified criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Datamart. Error: $errorDetails" -Level Error + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceByCapacity.ps1 b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceByCapacity.ps1 new file mode 100644 index 0000000..5669c14 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceByCapacity.ps1 @@ -0,0 +1,113 @@ +<# +.SYNOPSIS +Assigns workspaces to a Fabric domain based on specified capacities. + +.DESCRIPTION +The `Assign-FabricDomainWorkspaceByCapacity` function assigns workspaces to a Fabric domain using a list of capacity IDs by making a POST request to the relevant API endpoint. + +.PARAMETER DomainId +The unique identifier of the Fabric domain to which the workspaces will be assigned. + +.PARAMETER CapacitiesIds +An array of capacity IDs used to assign workspaces to the domain. + +.EXAMPLE +Assign-FabricDomainWorkspaceByCapacity -DomainId "12345" -CapacitiesIds @("capacity1", "capacity2") + +Assigns workspaces to the domain with ID "12345" based on the specified capacities. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Assign-FabricDomainWorkspaceByCapacity { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [array]$CapacitiesIds + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}/assignWorkspacesByCapacities" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + capacitiesIds = $CapacitiesIds + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Assigning domain workspaces by capacity completed successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Assigning domain workspaces by capacity is in progress for domain '$DomainId'." -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + return $operationStatus + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Error occurred while assigning workspaces by capacity for domain '$DomainId'. Details: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceById.ps1 b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceById.ps1 new file mode 100644 index 0000000..7c20edb --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceById.ps1 @@ -0,0 +1,83 @@ +<# +.SYNOPSIS +Assigns workspaces to a specified domain in Microsoft Fabric by their IDs. + +.DESCRIPTION +The `Assign-FabricDomainWorkspaceById` function sends a request to assign multiple workspaces to a specified domain using the provided domain ID and an array of workspace IDs. + +.PARAMETER DomainId +The ID of the domain to which workspaces will be assigned. This parameter is mandatory. + +.PARAMETER WorkspaceIds +An array of workspace IDs to be assigned to the domain. This parameter is mandatory. + +.EXAMPLE +Assign-FabricDomainWorkspaceById -DomainId "12345" -WorkspaceIds @("ws1", "ws2", "ws3") + +Assigns the workspaces with IDs "ws1", "ws2", and "ws3" to the domain with ID "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Assign-FabricDomainWorkspaceById { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [array]$WorkspaceIds + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}/assignWorkspaces" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + workspacesIds = $WorkspaceIds + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Successfully assigned workspaces to the domain with ID '$DomainId'." -Level Info + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to assign workspaces to the domain with ID '$DomainId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceByPrincipal.ps1 b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceByPrincipal.ps1 new file mode 100644 index 0000000..52f868e --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceByPrincipal.ps1 @@ -0,0 +1,119 @@ +<# +.SYNOPSIS +Assigns workspaces to a domain based on principal IDs in Microsoft Fabric. + +.DESCRIPTION +The `Assign-FabricDomainWorkspaceByPrincipal` function sends a request to assign workspaces to a specified domain using a JSON object of principal IDs and types. + +.PARAMETER DomainId +The ID of the domain to which workspaces will be assigned. This parameter is mandatory. + +.PARAMETER PrincipalIds +An array representing the principals with their `id` and `type` properties. Must contain a `principals` key with an array of objects. + +.EXAMPLE +$PrincipalIds = @( + @{id = "813abb4a-414c-4ac0-9c2c-bd17036fd58c"; type = "User"}, + @{id = "b5b9495c-685a-447a-b4d3-2d8e963e6288"; type = "User"} + ) + +Assign-FabricDomainWorkspaceByPrincipal -DomainId "12345" -PrincipalIds $principals + +Assigns the workspaces based on the provided principal IDs and types. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Assign-FabricDomainWorkspaceByPrincipal { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + #[hashtable]$PrincipalIds # Must contain a JSON array of principals with 'id' and 'type' properties + [System.Object]$PrincipalIds + ) + + try { + # Step 1: Ensure each principal contains 'id' and 'type' + foreach ($principal in $PrincipalIds) { + if (-not ($principal.ContainsKey('id') -and $principal.ContainsKey('type'))) { + throw "Each principal object must contain 'id' and 'type' properties." + } + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}/assignWorkspacesByPrincipals" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Message + + # Step 4: Construct the request body + $body = @{ + principals = $PrincipalIds + } + + # Convert the PrincipalIds to JSON + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 5: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 6: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Assigning domain workspaces by principal completed successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Assigning domain workspaces by principal is in progress for domain '$DomainId'." -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + return $operationStatus + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to assign domain workspaces by principals. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceRoleAssignment.ps1 b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceRoleAssignment.ps1 new file mode 100644 index 0000000..da306f7 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Assign-FabricDomainWorkspaceRoleAssignment.ps1 @@ -0,0 +1,102 @@ +<# +.SYNOPSIS +Bulk assigns roles to principals for workspaces in a Fabric domain. + +.DESCRIPTION +The `AssignFabricDomainWorkspaceRoleAssignment` function performs bulk role assignments for principals in a specific Fabric domain. It sends a POST request to the relevant API endpoint. + +.PARAMETER DomainId +The unique identifier of the Fabric domain where roles will be assigned. + +.PARAMETER DomainRole +The role to assign to the principals. Must be one of the following: +- `Admins` +- `Contributors` + +.PARAMETER PrincipalIds +An array of principals to assign roles to. Each principal must include: +- `id`: The identifier of the principal. +- `type`: The type of the principal (e.g., `User`, `Group`). + +.EXAMPLE +AssignFabricDomainWorkspaceRoleAssignment -DomainId "12345" -DomainRole "Admins" -PrincipalIds @(@{id="user1"; type="User"}, @{id="group1"; type="Group"}) + +Assigns the `Admins` role to the specified principals in the domain with ID "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Assign-FabricDomainWorkspaceRoleAssignment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Admins', 'Contributors')] + [string]$DomainRole, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [array]$PrincipalIds # Array with 'id' and 'type' + ) + + try { + # Step 1: Validate PrincipalIds structure + foreach ($principal in $PrincipalIds) { + if (-not ($principal.id -and $principal.type)) { + throw "Invalid principal detected: Each principal must include 'id' and 'type' properties. Found: $principal" + } + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}/roleAssignments/bulkAssign" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Construct the request body + $body = @{ + type = $DomainRole + principals = $PrincipalIds + } + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 5: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 6: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Bulk role assignment for domain '$DomainId' completed successfully!" -Level Info + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to bulk assign roles in domain '$DomainId'. Error: $errorDetails" -Level Error + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Domain/Get-FabricDomain.ps1 b/powershell/FabricACEToolkit/Public/Domain/Get-FabricDomain.ps1 new file mode 100644 index 0000000..31c8c1c --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Get-FabricDomain.ps1 @@ -0,0 +1,121 @@ +<# +.SYNOPSIS +Retrieves domain information from Microsoft Fabric, optionally filtering by domain ID, domain name, or only non-empty domains. + +.DESCRIPTION +The `Get-FabricDomain` function allows retrieval of domains in Microsoft Fabric, with optional filtering by domain ID or name. Additionally, it can filter to return only non-empty domains. + +.PARAMETER DomainId +(Optional) The ID of the domain to retrieve. + +.PARAMETER DomainName +(Optional) The display name of the domain to retrieve. + +.PARAMETER NonEmptyDomainsOnly +(Optional) If set to `$true`, only domains containing workspaces will be returned. + +.EXAMPLE +Get-FabricDomain -DomainId "12345" + +Fetches the domain with ID "12345". + +.EXAMPLE +Get-FabricDomain -DomainName "Finance" + +Fetches the domain with the display name "Finance". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> +function Get-FabricDomain { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DomainName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$NonEmptyDomainsOnly = $false + ) + + try { + # Step 1: Handle ambiguous input + if ($DomainId -and $DomainName) { + Write-Message -Message "Both 'DomainId' and 'DomainName' were provided. Please specify only one." -Level Error + return @() + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL with filtering logic + $apiEndpointUrl = "{0}/admin/domains" -f $FabricConfig.BaseUrl + if ($NonEmptyDomainsOnly) { + $apiEndpointUrl = "{0}?nonEmptyOnly=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle empty response + if (-not $response) { + Write-Message -Message "No data returned from the API." -Level Warning + return $null + } + + + # Step 7: Filter results based on provided parameters + $domains = if ($DomainId) { + $response.domains | Where-Object { $_.Id -eq $DomainId } + } + elseif ($DomainName) { + $response.domains | Where-Object { $_.DisplayName -eq $DomainName } + } + else { + # Return all domains if no filter is provided + Write-Message -Message "No filter provided. Returning all domains." -Level Debug + return $response.domains + } + + # Step 8: Handle results + if ($domains) { + return $domains + } + else { + Write-Message -Message "No domain found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve environment. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Domain/Get-FabricDomainWorkspace.ps1 b/powershell/FabricACEToolkit/Public/Domain/Get-FabricDomainWorkspace.ps1 new file mode 100644 index 0000000..4094ab3 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Get-FabricDomainWorkspace.ps1 @@ -0,0 +1,80 @@ +<# +.SYNOPSIS +Retrieves the workspaces associated with a specific domain in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricDomainWorkspace` function fetches the workspaces for the given domain ID. + +.PARAMETER DomainId +The ID of the domain for which to retrieve workspaces. + +.EXAMPLE +Get-FabricDomainWorkspace -DomainId "12345" + +Fetches workspaces for the domain with ID "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricDomainWorkspace { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}/workspaces" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 5: Handle empty response + if (-not $response) { + Write-Message -Message "No data returned from the API." -Level Warning + return $null + } + # Step 6: Handle results + if ($response) { + return $response.value + } + else { + Write-Message -Message "No workspace found for the '$DomainId'." -Level Warning + return $null + } + + } + catch { + # Step 7: Capture and log error details + $errorDetails = Get-ErrorResponse($_.Exception) + Write-Message -Message "Failed to retrieve domain workspaces. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Domain/New-FabricDomain.ps1 b/powershell/FabricACEToolkit/Public/Domain/New-FabricDomain.ps1 new file mode 100644 index 0000000..e60c904 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/New-FabricDomain.ps1 @@ -0,0 +1,128 @@ +<# +.SYNOPSIS +Creates a new Fabric domain. + +.DESCRIPTION +The `Add-FabricDomain` function creates a new domain in Microsoft Fabric by making a POST request to the relevant API endpoint. + +.PARAMETER DomainName +The name of the domain to be created. Must only contain alphanumeric characters, underscores, and spaces. + +.PARAMETER DomainDescription +A description of the domain to be created. + +.PARAMETER ParentDomainId +(Optional) The ID of the parent domain, if applicable. + +.EXAMPLE +Add-FabricDomain -DomainName "Finance" -DomainDescription "Finance data domain" -ParentDomainId "12345" + +Creates a "Finance" domain under the parent domain with ID "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricDomain { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$DomainName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DomainDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ParentDomainId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the request body + $apiEndpointUrl = "{0}/admin/domains" -f $FabricConfig.BaseUrl + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Construct the request body + $body = @{ + displayName = $DomainName + } + + if ($DomainDescription) { + $body.description = $DomainDescription + } + + if ($ParentDomainId) { + $body.parentDomainId = $ParentDomainId + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Domain '$DomainName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Domain '$DomainName' creation accepted. Provisioning in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create domain. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Domain/Remove-FabricDomain.ps1 b/powershell/FabricACEToolkit/Public/Domain/Remove-FabricDomain.ps1 new file mode 100644 index 0000000..c710315 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Remove-FabricDomain.ps1 @@ -0,0 +1,68 @@ +<# +.SYNOPSIS +Deletes a Fabric domain by its ID. + +.DESCRIPTION +The `Remove-FabricDomain` function removes a specified domain from Microsoft Fabric by making a DELETE request to the relevant API endpoint. + +.PARAMETER DomainId +The unique identifier of the domain to be deleted. + +.EXAMPLE +Remove-FabricDomain -DomainId "12345" + +Deletes the domain with ID "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricDomain { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Domain '$DomainId' deleted successfully!" -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete domain '$DomainId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Domain/Unassign-FabricDomainWorkspace.ps1 b/powershell/FabricACEToolkit/Public/Domain/Unassign-FabricDomainWorkspace.ps1 new file mode 100644 index 0000000..d86afbd --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Unassign-FabricDomainWorkspace.ps1 @@ -0,0 +1,96 @@ + +<# +.SYNOPSIS +Unassign workspaces from a specified Fabric domain. + +.DESCRIPTION +The `Unassign -FabricDomainWorkspace` function allows you to Unassign specific workspaces from a given Fabric domain or unassign all workspaces if no workspace IDs are specified. +It makes a POST request to the relevant API endpoint for this operation. + +.PARAMETER DomainId +The unique identifier of the Fabric domain. + +.PARAMETER WorkspaceIds +(Optional) An array of workspace IDs to unassign. If not provided, all workspaces will be unassigned. + +.EXAMPLE +Unassign-FabricDomainWorkspace -DomainId "12345" + +Unassigns all workspaces from the domain with ID "12345". + +.EXAMPLE +Unassign-FabricDomainWorkspace -DomainId "12345" -WorkspaceIds @("workspace1", "workspace2") + +Unassigns the specified workspaces from the domain with ID "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + + +Author: Tiago Balabuch + +#> +function Unassign-FabricDomainWorkspace { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [array]$WorkspaceIds + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + # Determine the API endpoint URL based on the presence of WorkspaceIds + $endpointSuffix = if ($WorkspaceIds) { "unassignWorkspaces" } else { "unassignAllWorkspaces" } + + $apiEndpointUrl = "{0}/admin/domains/{1}/{2}" -f $FabricConfig.BaseUrl, $DomainId, $endpointSuffix + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + + # Step 3: Construct the request body (if needed) + $bodyJson = if ($WorkspaceIds) { + $body = @{ workspacesIds = $WorkspaceIds } + $body | ConvertTo-Json -Depth 2 + } + else { + $null + } + + Write-Message -Message "Request Body: $bodyJson" -Level Debug + # Step 4: Make the API request to unassign specific workspaces + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Successfully unassigned workspaces to the domain with ID '$DomainId'." -Level Info + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to unassign workspaces to the domain with ID '$DomainId'. Error: $errorDetails" -Level Error + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Domain/Unassign-FabricDomainWorkspaceRoleAssignment.ps1 b/powershell/FabricACEToolkit/Public/Domain/Unassign-FabricDomainWorkspaceRoleAssignment.ps1 new file mode 100644 index 0000000..c818fbb --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Unassign-FabricDomainWorkspaceRoleAssignment.ps1 @@ -0,0 +1,103 @@ +<# +.SYNOPSIS +Bulk unUnassign roles to principals for workspaces in a Fabric domain. + +.DESCRIPTION +The `AssignFabricDomainWorkspaceRoleAssignment` function performs bulk role assignments for principals in a specific Fabric domain. It sends a POST request to the relevant API endpoint. + +.PARAMETER DomainId +The unique identifier of the Fabric domain where roles will be assigned. + +.PARAMETER DomainRole +The role to assign to the principals. Must be one of the following: +- `Admins` +- `Contributors` + +.PARAMETER PrincipalIds +An array of principals to assign roles to. Each principal must include: +- `id`: The identifier of the principal. +- `type`: The type of the principal (e.g., `User`, `Group`). + +.EXAMPLE +AssignFabricDomainWorkspaceRoleAssignment -DomainId "12345" -DomainRole "Admins" -PrincipalIds @(@{id="user1"; type="User"}, @{id="group1"; type="Group"}) + +Unassign the `Admins` role to the specified principals in the domain with ID "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Unassign-FabricDomainWorkspaceRoleAssignment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Admins', 'Contributors')] + [string]$DomainRole, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [array]$PrincipalIds # Array with 'id' and 'type' + ) + + try { + # Step 1: Validate PrincipalIds structure + foreach ($principal in $PrincipalIds) { + if (-not ($principal.id -and $principal.type)) { + throw "Invalid principal detected: Each principal must include 'id' and 'type' properties. Found: $principal" + } + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}/roleAssignments/bulkUnassign" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Construct the request body + $body = @{ + type = $DomainRole + principals = $PrincipalIds + } + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 5: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 6: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Bulk role unassignment for domain '$DomainId' completed successfully!" -Level Info + + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to bulk assign roles in domain '$DomainId'. Error: $errorDetails" -Level Error + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Domain/Update-FabricDomain.ps1 b/powershell/FabricACEToolkit/Public/Domain/Update-FabricDomain.ps1 new file mode 100644 index 0000000..0ffad31 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Domain/Update-FabricDomain.ps1 @@ -0,0 +1,112 @@ +<# +.SYNOPSIS +Updates a Fabric domain by its ID. + +.DESCRIPTION +The `Update-FabricDomain` function modifies a specified domain in Microsoft Fabric using the provided parameters. + +.PARAMETER DomainId +The unique identifier of the domain to be updated. + +.PARAMETER DomainName +The new name for the domain. Must be alphanumeric. + +.PARAMETER DomainDescription +(Optional) A new description for the domain. + +.PARAMETER DomainContributorsScope +(Optional) The contributors' scope for the domain. Accepted values: 'AdminsOnly', 'AllTenant', 'SpecificUsersAndGroups'. + +.EXAMPLE +Update-FabricDomain -DomainId "12345" -DomainName "NewDomain" -DomainDescription "Updated description" -DomainContributorsScope "AdminsOnly" + +Updates the domain with ID "12345" with a new name, description, and contributors' scope. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricDomain { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$DomainName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DomainDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('AdminsOnly', 'AllTenant', 'SpecificUsersAndGroups')] + [string]$DomainContributorsScope + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/admin/domains/{1}" -f $FabricConfig.BaseUrl, $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $DomainName + } + + if ($DomainDescription) { + $body.description = $DomainDescription + } + + if ($DomainContributorsScope) { + $body.contributorsScope = $DomainContributorsScope + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Domain '$DomainName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update domain '$DomainId'. Error: $errorDetails" -Level Error + } +} + \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironment.ps1 b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironment.ps1 new file mode 100644 index 0000000..48e497c --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironment.ps1 @@ -0,0 +1,157 @@ +<# +.SYNOPSIS +Retrieves an environment or a list of environments from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricEnvironment` function sends a GET request to the Fabric API to retrieve environment details for a given workspace. It can filter the results by `EnvironmentName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query environments. + +.PARAMETER EnvironmentName +(Optional) The name of the specific environment to retrieve. + +.EXAMPLE +Get-FabricEnvironment -WorkspaceId "12345" -EnvironmentName "Development" + +Retrieves the "Development" environment from workspace "12345". + +.EXAMPLE +Get-FabricEnvironment -WorkspaceId "12345" + +Retrieves all environments in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Returns the matching environment details or all environments if no filter is provided. + +Author: Tiago Balabuch + +#> + +function Get-FabricEnvironment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EnvironmentName + ) + + try { + # Step 1: Handle ambiguous input + if ($EnvironmentId -and $EnvironmentName) { + Write-Message -Message "Both 'EnvironmentId' and 'EnvironmentName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $environments = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + $baseApiEndpointUrl = "{0}/workspaces/{1}/environments" -f $FabricConfig.BaseUrl, $WorkspaceId + + # Step 4: Loop to retrieve data with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $environments += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $environment = if ($EnvironmentId) { + $environments | Where-Object { $_.Id -eq $EnvironmentId } + } + elseif ($EnvironmentName) { + $environments | Where-Object { $_.DisplayName -eq $EnvironmentName } + } + else { + # Return all workspaces if no filter is provided + Write-Message -Message "No filter provided. Returning all environments." -Level Debug + $environments + } + + # Step 9: Handle results + if ($environment) { + Write-Message -Message "Environment found in the Workspace '$WorkspaceId'." -Level Debug + return $environment + } + else { + Write-Message -Message "No environment found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve environment. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentLibrary.ps1 b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentLibrary.ps1 new file mode 100644 index 0000000..75a650a --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentLibrary.ps1 @@ -0,0 +1,76 @@ +<# +.SYNOPSIS +Retrieves the list of libraries associated with a specific environment in a Microsoft Fabric workspace. + +.DESCRIPTION +The Get-FabricEnvironmentLibrary function fetches library information for a given workspace and environment +using the Microsoft Fabric API. It ensures the authentication token is valid and validates the response +to handle errors gracefully. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace where the environment is located. + +.PARAMETER EnvironmentId +The unique identifier of the environment whose libraries are being queried. + +.EXAMPLE +Get-FabricEnvironmentLibrary -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" + +Retrieves the libraries associated with the specified environment in the given workspace. + +.NOTES +- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. +- Uses `Test-TokenExpired` to validate the token before making API calls. + +Author: Tiago Balabuch +#> +function Get-FabricEnvironmentLibrary { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/libraries" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 5: Handle results + return $response + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve environment libraries. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 new file mode 100644 index 0000000..65cf74d --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 @@ -0,0 +1,76 @@ +<# +.SYNOPSIS +Retrieves the Spark compute details for a specific environment in a Microsoft Fabric workspace. + +.DESCRIPTION +The Get-FabricEnvironmentSparkCompute function communicates with the Microsoft Fabric API to fetch information +about Spark compute resources associated with a specified environment. It ensures that the API token is valid +and gracefully handles errors during the API call. + +.PARAMETER WorkspaceId +The unique identifier of the workspace containing the target environment. + +.PARAMETER EnvironmentId +The unique identifier of the environment whose Spark compute details are being retrieved. + +.EXAMPLE +Get-FabricEnvironmentSparkCompute -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" + +Retrieves Spark compute details for the specified environment in the given workspace. + +.NOTES +- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. +- Uses `Test-TokenExpired` to validate the token before making API calls. + +Author: Tiago Balabuch +#> +function Get-FabricEnvironmentSparkCompute { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/sparkcompute" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 5: Handle results + return $response + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve environment Spark compute. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 new file mode 100644 index 0000000..0a8a550 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 @@ -0,0 +1,76 @@ +<# +.SYNOPSIS +Retrieves the staging library details for a specific environment in a Microsoft Fabric workspace. + +.DESCRIPTION +The Get-FabricEnvironmentStagingLibrary function interacts with the Microsoft Fabric API to fetch information +about staging libraries associated with a specified environment. It ensures token validity and handles API errors gracefully. + +.PARAMETER WorkspaceId +The unique identifier of the workspace containing the target environment. + +.PARAMETER EnvironmentId +The unique identifier of the environment for which staging library details are being retrieved. + +.EXAMPLE + Get-FabricEnvironmentStagingLibrary -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" + +Retrieves the staging libraries for the specified environment in the given workspace. + +.NOTES +- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. +- Uses `Test-TokenExpired` to validate the token before making API calls. + +Author: Tiago Balabuch +#> +function Get-FabricEnvironmentStagingLibrary { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/libraries" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 5: Handle results + return $response.customLibraries + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve environment spark compute. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 new file mode 100644 index 0000000..cbc94d5 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 @@ -0,0 +1,78 @@ +<# +.SYNOPSIS +Retrieves staging Spark compute details for a specific environment in a Microsoft Fabric workspace. + +.DESCRIPTION +The Get-FabricEnvironmentStagingSparkCompute function interacts with the Microsoft Fabric API to fetch information +about staging Spark compute configurations for a specified environment. It ensures token validity and handles API errors gracefully. + +.PARAMETER WorkspaceId +The unique identifier of the workspace containing the target environment. + +.PARAMETER EnvironmentId +The unique identifier of the environment for which staging Spark compute details are being retrieved. + +.EXAMPLE +Get-FabricEnvironmentStagingSparkCompute -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" + +Retrieves the staging Spark compute configurations for the specified environment in the given workspace. + +.NOTES +- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. +- Uses `Test-TokenExpired` to validate the token before making API calls. + +Author: Tiago Balabuch +#> + + +function Get-FabricEnvironmentStagingSparkCompute { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/sparkcompute" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 5: Handle results + return $response + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve environment spark compute. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Environment/New-FabricEnvironment.ps1 b/powershell/FabricACEToolkit/Public/Environment/New-FabricEnvironment.ps1 new file mode 100644 index 0000000..009a5ae --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/New-FabricEnvironment.ps1 @@ -0,0 +1,123 @@ +<# +.SYNOPSIS +Creates a new environment in a specified workspace. + +.DESCRIPTION +The `Add-FabricEnvironment` function creates a new environment within a given workspace by making a POST request to the Fabric API. The environment can optionally include a description. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace where the environment will be created. + +.PARAMETER EnvironmentName +(Mandatory) The name of the environment to be created. Only alphanumeric characters, spaces, and underscores are allowed. + +.PARAMETER EnvironmentDescription +(Optional) A description of the environment. + +.EXAMPLE +Add-FabricEnvironment -WorkspaceId "12345" -EnvironmentName "DevEnv" -EnvironmentDescription "Development Environment" + +Creates an environment named "DevEnv" in workspace "12345" with the specified description. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricEnvironment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EnvironmentName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $EnvironmentName + } + + if ($EnvironmentDescription) { + $body.description = $EnvironmentDescription + } + + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Environment '$EnvironmentName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Environment '$EnvironmentName' creation accepted. Provisioning in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create environment. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Publish-FabricEnvironment.ps1 b/powershell/FabricACEToolkit/Public/Environment/Publish-FabricEnvironment.ps1 new file mode 100644 index 0000000..bf9fffb --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Publish-FabricEnvironment.ps1 @@ -0,0 +1,104 @@ +<# +.SYNOPSIS +Publishes a staging environment in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function interacts with the Microsoft Fabric API to initiate the publishing process for a staging environment. +It validates the authentication token, constructs the API request, and handles both immediate and long-running operations. + + +.PARAMETER WorkspaceId +The unique identifier of the workspace containing the staging environment. + +.PARAMETER EnvironmentId +The unique identifier of the staging environment to be published. + +.EXAMPLE +Publish-FabricEnvironment -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" + +Initiates the publishing process for the specified staging environment. + +.NOTES +- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. +- Uses `Test-TokenExpired` to validate the token before making API calls. + +Author: Tiago Balabuch +#> + +function Publish-FabricEnvironment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/publish" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Publish operation request has been submitted successfully for the environment '$EnvironmentId'!" -Level Info + return $response.publishDetails + } + 202 { + Write-Message -Message "Publish operation accepted. Publishing in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create environment. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Remove-FabricEnvironment.ps1 b/powershell/FabricACEToolkit/Public/Environment/Remove-FabricEnvironment.ps1 new file mode 100644 index 0000000..4e1f734 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Remove-FabricEnvironment.ps1 @@ -0,0 +1,74 @@ +<# +.SYNOPSIS +Deletes an environment from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricEnvironment` function sends a DELETE request to the Fabric API to remove a specified environment from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the environment to delete. + +.PARAMETER EnvironmentId +(Mandatory) The ID of the environment to be deleted. + +.EXAMPLE +Remove-FabricEnvironment -WorkspaceId "12345" -EnvironmentId "67890" + +Deletes the environment with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricEnvironment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Environment '$EnvironmentId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete environment '$EnvironmentId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 b/powershell/FabricACEToolkit/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 new file mode 100644 index 0000000..ebfd16f --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 @@ -0,0 +1,85 @@ + +<# +.SYNOPSIS +Deletes a specified library from the staging environment in a Microsoft Fabric workspace. + +.DESCRIPTION +This function allows for the deletion of a library from the staging environment, one file at a time. +It ensures token validity, constructs the appropriate API request, and handles both success and failure responses. + +.PARAMETER WorkspaceId +The unique identifier of the workspace from which the library is to be deleted. + +.PARAMETER EnvironmentId +The unique identifier of the staging environment containing the library. + +.PARAMETER LibraryName +The name of the library to be deleted from the environment. + +.EXAMPLE +Remove-FabricEnvironmentStagingLibrary -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" -LibraryName "library-to-delete" + +Deletes the specified library from the staging environment in the specified workspace. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. +- This function currently supports deleting one library at a time. +Author: Tiago Balabuch + +#> + + +function Remove-FabricEnvironmentStagingLibrary { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$LibraryName + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/libraries?libraryToDelete={3}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId, $LibraryName + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Staging library $LibraryName for the Environment '$EnvironmentId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete environment '$EnvironmentId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Stop-FabricEnvironmentPublish.ps1 b/powershell/FabricACEToolkit/Public/Environment/Stop-FabricEnvironmentPublish.ps1 new file mode 100644 index 0000000..9276ea0 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Stop-FabricEnvironmentPublish.ps1 @@ -0,0 +1,76 @@ +<# +.SYNOPSIS +Cancels the publish operation for a specified environment in Microsoft Fabric. + +.DESCRIPTION +This function sends a cancel publish request to the Microsoft Fabric API for a given environment. +It ensures that the token is valid before making the request and handles both successful and error responses. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the environment exists. + +.PARAMETER EnvironmentId +The unique identifier of the environment for which the publish operation is to be canceled. + +.EXAMPLE +Stop-FabricEnvironmentPublish -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" + +Cancels the publish operation for the specified environment. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> +function Stop-FabricEnvironmentPublish{ + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/cancelPublish" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Publication for environment '$EnvironmentId' has been successfully canceled." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to cancel publication for environment '$EnvironmentId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Update-FabricEnvironment.ps1 b/powershell/FabricACEToolkit/Public/Environment/Update-FabricEnvironment.ps1 new file mode 100644 index 0000000..2c9364b --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Update-FabricEnvironment.ps1 @@ -0,0 +1,108 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric Environment. + +.DESCRIPTION +The `Update-FabricEnvironment` function updates the name and/or description of a specified Fabric Environment by making a PATCH request to the API. + +.PARAMETER EnvironmentId +The unique identifier of the Environment to be updated. + +.PARAMETER EnvironmentName +The new name for the Environment. + +.PARAMETER EnvironmentDescription +(Optional) The new description for the Environment. + +.EXAMPLE +Update-FabricEnvironment -EnvironmentId "Environment123" -EnvironmentName "NewEnvironmentName" + +Updates the name of the Environment with the ID "Environment123" to "NewEnvironmentName". + +.EXAMPLE +Update-FabricEnvironment -EnvironmentId "Environment123" -EnvironmentName "NewName" -EnvironmentDescription "Updated description" + +Updates both the name and description of the Environment "Environment123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricEnvironment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EnvironmentName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $EnvironmentName + } + + if ($EnvironmentDescription) { + $body.description = $EnvironmentDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Environment '$EnvironmentName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Environment. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 b/powershell/FabricACEToolkit/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 new file mode 100644 index 0000000..bd54262 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 @@ -0,0 +1,177 @@ +<# +.SYNOPSIS +Updates the Spark compute configuration in the staging environment for a given workspace. + +.DESCRIPTION +This function sends a PATCH request to the Microsoft Fabric API to update the Spark compute settings +for a specified environment, including instance pool, driver and executor configurations, and dynamic allocation settings. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the environment exists. + +.PARAMETER EnvironmentId +The unique identifier of the environment where the Spark compute settings will be updated. + +.PARAMETER InstancePoolName +The name of the instance pool to be used for Spark compute. + +.PARAMETER InstancePoolType +The type of instance pool (either 'Workspace' or 'Capacity'). + +.PARAMETER DriverCores +The number of cores to allocate to the driver. + +.PARAMETER DriverMemory +The amount of memory to allocate to the driver. + +.PARAMETER ExecutorCores +The number of cores to allocate to each executor. + +.PARAMETER ExecutorMemory +The amount of memory to allocate to each executor. + +.PARAMETER DynamicExecutorAllocationEnabled +Boolean flag to enable or disable dynamic executor allocation. + +.PARAMETER DynamicExecutorAllocationMinExecutors +The minimum number of executors when dynamic allocation is enabled. + +.PARAMETER DynamicExecutorAllocationMaxExecutors +The maximum number of executors when dynamic allocation is enabled. + +.PARAMETER RuntimeVersion +The Spark runtime version to use. + +.PARAMETER SparkProperties +A hashtable of additional Spark properties to configure. + +.EXAMPLE +Update-FabricEnvironmentStagingSparkCompute -WorkspaceId "workspace-12345" -EnvironmentId "env-67890" -InstancePoolName "pool1" -InstancePoolType "Workspace" -DriverCores 4 -DriverMemory "16GB" -ExecutorCores 8 -ExecutorMemory "32GB" -DynamicExecutorAllocationEnabled $true -DynamicExecutorAllocationMinExecutors 2 -DynamicExecutorAllocationMaxExecutors 10 -RuntimeVersion "3.1" -SparkProperties @{ "spark.executor.memoryOverhead"="4GB" } + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> +function Update-FabricEnvironmentStagingSparkCompute { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$InstancePoolName, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Workspace', 'Capacity')] + [string]$InstancePoolType, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$DriverCores, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DriverMemory, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$ExecutorCores, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ExecutorMemory, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [bool]$DynamicExecutorAllocationEnabled, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$DynamicExecutorAllocationMinExecutors, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$DynamicExecutorAllocationMaxExecutors, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$RuntimeVersion, + + [Parameter(Mandatory = $true)] + [System.Object]$SparkProperties + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/sparkcompute" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + instancePool = @{ + name = $InstancePoolName + type = $InstancePoolType + } + driverCores = $DriverCores + driverMemory = $DriverMemory + executorCores = $ExecutorCores + executorMemory = $ExecutorMemory + dynamicExecutorAllocation = @{ + enabled = $DynamicExecutorAllocationEnabled + minExecutors = $DynamicExecutorAllocationMinExecutors + maxExecutors = $DynamicExecutorAllocationMaxExecutors + } + runtimeVersion = $RuntimeVersion + sparkProperties = $SparkProperties + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 4 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Environment staging Spark compute updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update environment staging Spark compute. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Environment/Upload-FabricEnvironmentStagingLibrary.ps1 b/powershell/FabricACEToolkit/Public/Environment/Upload-FabricEnvironmentStagingLibrary.ps1 new file mode 100644 index 0000000..d8b0996 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Environment/Upload-FabricEnvironmentStagingLibrary.ps1 @@ -0,0 +1,79 @@ +<# +.SYNOPSIS +Uploads a library to the staging environment in a Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to upload a library to the specified +environment staging area for the given workspace. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the environment exists. + +.PARAMETER EnvironmentId +The unique identifier of the environment where the library will be uploaded. + +.EXAMPLE +Upload-FabricEnvironmentStagingLibrary -WorkspaceId "workspace-12345" -EnvironmentId "env-67890" + +.NOTES +- This is not working code. It is a placeholder for future development. Fabric documentation is missing some important details on how to upload libraries. +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> +function Upload-FabricEnvironmentStagingLibrary { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/libraries" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Environment staging library uploaded successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to upload environment staging library. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventhouse/Get-FabricEventhouse.ps1 b/powershell/FabricACEToolkit/Public/Eventhouse/Get-FabricEventhouse.ps1 new file mode 100644 index 0000000..dabafa4 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventhouse/Get-FabricEventhouse.ps1 @@ -0,0 +1,156 @@ +<# +.SYNOPSIS + Retrieves Eventhouse details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves Eventhouse details from a specified workspace using either the provided EventhouseId or EventhouseName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Eventhouse exists. This parameter is mandatory. + +.PARAMETER EventhouseId + The unique identifier of the Eventhouse to retrieve. This parameter is optional. + +.PARAMETER EventhouseName + The name of the Eventhouse to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricEventhouse -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" + This example retrieves the Eventhouse details for the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricEventhouse -WorkspaceId "workspace-12345" -EventhouseName "My Eventhouse" + This example retrieves the Eventhouse details for the Eventhouse named "My Eventhouse" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricEventhouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EventhouseName + ) + try { + + # Step 1: Handle ambiguous input + if ($EventhouseId -and $EventhouseName) { + Write-Message -Message "Both 'EventhouseId' and 'EventhouseName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $eventhouses = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/eventhouses" -f $FabricConfig.BaseUrl, $WorkspaceId + # Step 3: Loop to retrieve data with continuation token + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $eventhouses += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $eventhouse = if ($EventhouseId) { + $eventhouses | Where-Object { $_.Id -eq $EventhouseId } + } + elseif ($EventhouseName) { + $eventhouses | Where-Object { $_.DisplayName -eq $EventhouseName } + } + else { + # Return all eventhouses if no filter is provided + Write-Message -Message "No filter provided. Returning all Eventhouses." -Level Debug + $eventhouses + } + + # Step 9: Handle results + if ($eventhouse) { + Write-Message -Message "Eventhouse found in the Workspace '$WorkspaceId'." -Level Debug + return $eventhouse + } + else { + Write-Message -Message "No Eventhouse found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventhouse. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 b/powershell/FabricACEToolkit/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 new file mode 100644 index 0000000..e42a8a1 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 @@ -0,0 +1,124 @@ +<# +.SYNOPSIS + Retrieves the definition of an Eventhouse from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves the definition of an Eventhouse from a specified workspace using the provided EventhouseId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Eventhouse exists. This parameter is mandatory. + +.PARAMETER EventhouseId + The unique identifier of the Eventhouse to retrieve the definition for. This parameter is optional. + +.PARAMETER EventhouseFormat + The format in which to retrieve the Eventhouse definition. This parameter is optional. + +.EXAMPLE + Get-FabricEventhouseDefinition -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" + This example retrieves the definition of the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricEventhouseDefinition -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" -EventhouseFormat "json" + This example retrieves the definition of the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345" in JSON format. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricEventhouseDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseFormat + ) + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventhouseId + + if ($EventhouseFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $EventhouseFormat + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "Eventhouse '$EventhouseId' definition retrieved successfully!" -Level Debug + return $response + } + 202 { + + Write-Message -Message "Getting Eventhouse '$EventhouseId' definition request accepted. Retrieving in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventhouse. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Eventhouse/New-FabricEventhouse.ps1 b/powershell/FabricACEToolkit/Public/Eventhouse/New-FabricEventhouse.ps1 new file mode 100644 index 0000000..de5979b --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventhouse/New-FabricEventhouse.ps1 @@ -0,0 +1,193 @@ +<# +.SYNOPSIS + Creates a new Eventhouse in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new Eventhouse + in the specified workspace. It supports optional parameters for Eventhouse description and path definitions. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Eventhouse will be created. This parameter is mandatory. + +.PARAMETER EventhouseName + The name of the Eventhouse to be created. This parameter is mandatory. + +.PARAMETER EventhouseDescription + An optional description for the Eventhouse. + +.PARAMETER EventhousePathDefinition + An optional path to the Eventhouse definition file to upload. + +.PARAMETER EventhousePathPlatformDefinition + An optional path to the platform-specific definition file to upload. + +.EXAMPLE + New-FabricEventhouse -WorkspaceId "workspace-12345" -EventhouseName "New Eventhouse" -EventhouseDescription "Description of the new Eventhouse" + This example creates a new Eventhouse named "New Eventhouse" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function New-FabricEventhouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EventhouseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhousePathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhousePathPlatformDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $EventhouseName + } + + if ($EventhouseDescription) { + $body.description = $EventhouseDescription + } + if ($EventhousePathDefinition) { + $eventhouseEncodedContent = Convert-ToBase64 -filePath $EventhousePathDefinition + + if (-not [string]::IsNullOrEmpty($eventhouseEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "EventhouseProperties.json" + payload = $eventhouseEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in Eventhouse definition." -Level Error + return $null + } + } + + if ($EventhousePathPlatformDefinition) { + $eventhouseEncodedPlatformContent = Convert-ToBase64 -filePath $EventhousePathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($eventhouseEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $eventhouseEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "Response Code: $statusCode" -Level Debug + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Eventhouse '$EventhouseName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Eventhouse '$EventhouseName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Eventhouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventhouse/Remove-FabricEventhouse.ps1 b/powershell/FabricACEToolkit/Public/Eventhouse/Remove-FabricEventhouse.ps1 new file mode 100644 index 0000000..0bdfd27 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventhouse/Remove-FabricEventhouse.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS + Removes an Eventhouse from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove an Eventhouse + from the specified workspace using the provided WorkspaceId and EventhouseId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the Eventhouse will be removed. + +.PARAMETER EventhouseId + The unique identifier of the Eventhouse to be removed. + +.EXAMPLE + Remove-FabricEventhouse -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" + This example removes the Eventhouse with ID "eventhouse-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Remove-FabricEventhouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventhouseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle response + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Eventhouse '$EventhouseId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete Eventhouse '$EventhouseId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventhouse/Update-FabricEventhouse.ps1 b/powershell/FabricACEToolkit/Public/Eventhouse/Update-FabricEventhouse.ps1 new file mode 100644 index 0000000..6968c89 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventhouse/Update-FabricEventhouse.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS + Updates an existing Eventhouse in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing Eventhouse + in the specified workspace. It supports optional parameters for Eventhouse description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Eventhouse exists. This parameter is optional. + +.PARAMETER EventhouseId + The unique identifier of the Eventhouse to be updated. This parameter is mandatory. + +.PARAMETER EventhouseName + The new name of the Eventhouse. This parameter is mandatory. + +.PARAMETER EventhouseDescription + An optional new description for the Eventhouse. + +.EXAMPLE + Update-FabricEventhouse -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" -EventhouseName "Updated Eventhouse" -EventhouseDescription "Updated description" + This example updates the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricEventhouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EventhouseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseDescription + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventhouseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $EventhouseName + } + + if ($EventhouseDescription) { + $body.description = $EventhouseDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Eventhouse '$EventhouseName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Eventhouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 b/powershell/FabricACEToolkit/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 new file mode 100644 index 0000000..aa1bf71 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 @@ -0,0 +1,168 @@ +<# +.SYNOPSIS + Updates the definition of an existing Eventhouse in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update the definition of an existing Eventhouse + in the specified workspace. It supports optional parameters for Eventhouse definition and platform-specific definition. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Eventhouse exists. This parameter is mandatory. + +.PARAMETER EventhouseId + The unique identifier of the Eventhouse to be updated. This parameter is mandatory. + +.PARAMETER EventhousePathDefinition + An optional path to the Eventhouse definition file to upload. + +.PARAMETER EventhousePathPlatformDefinition + An optional path to the platform-specific definition file to upload. + +.EXAMPLE + Update-FabricEventhouseDefinition -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" -EventhousePathDefinition "C:\Path\To\EventhouseDefinition.json" + This example updates the definition of the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345" using the provided definition file. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricEventhouseDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventhousePathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhousePathPlatformDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventhouseId + + #if ($UpdateMetadata -eq $true) { + if($EventhousePathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + parts = @() + } + } + + if ($EventhousePathDefinition) { + $EventhouseEncodedContent = Convert-ToBase64 -filePath $EventhousePathDefinition + + if (-not [string]::IsNullOrEmpty($EventhouseEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "EventhouseProperties.json" + payload = $EventhouseEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in Eventhouse definition." -Level Error + return $null + } + } + + if ($EventhousePathPlatformDefinition) { + $EventhouseEncodedPlatformContent = Convert-ToBase64 -filePath $EventhousePathPlatformDefinition + if (-not [string]::IsNullOrEmpty($EventhouseEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $EventhouseEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for Eventhouse '$EventhouseId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for Eventhouse '$EventhouseId' accepted. Operation in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Eventhouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventstream/Get-FabricEventstream.ps1 b/powershell/FabricACEToolkit/Public/Eventstream/Get-FabricEventstream.ps1 new file mode 100644 index 0000000..28f6448 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventstream/Get-FabricEventstream.ps1 @@ -0,0 +1,159 @@ +<# +.SYNOPSIS +Retrieves an Eventstream or a list of Eventstreams from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricEventstream` function sends a GET request to the Fabric API to retrieve Eventstream details for a given workspace. It can filter the results by `EventstreamName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query Eventstreams. + +.PARAMETER EventstreamName +(Optional) The name of the specific Eventstream to retrieve. + +.EXAMPLE +Get-FabricEventstream -WorkspaceId "12345" -EventstreamName "Development" + +Retrieves the "Development" Eventstream from workspace "12345". + +.EXAMPLE +Get-FabricEventstream -WorkspaceId "12345" + +Retrieves all Eventstreams in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricEventstream { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EventstreamName + ) + + try { + # Step 1: Handle ambiguous input + if ($EventstreamId -and $EventstreamName) { + Write-Message -Message "Both 'EventstreamId' and 'EventstreamName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + $continuationToken = $null + $eventstreams = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/eventstreams" -f $FabricConfig.BaseUrl, $WorkspaceId + + # Step 3: Loop to retrieve data with continuation token + + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $eventstreams += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + + # Step 8: Filter results based on provided parameters + $eventstream = if ($EventstreamId) { + $eventstreams | Where-Object { $_.Id -eq $EventstreamId } + } + elseif ($EventstreamName) { + $eventstreams | Where-Object { $_.DisplayName -eq $EventstreamName } + } + else { + # Return all eventstreams if no filter is provided + Write-Message -Message "No filter provided. Returning all Eventstreams." -Level Debug + $eventstreams + } + + # Step 9: Handle results + if ($eventstream) { + Write-Message -Message "Eventstream found matching the specified criteria." -Level Debug + return $eventstream + } + else { + Write-Message -Message "No Eventstream found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventstream. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 b/powershell/FabricACEToolkit/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 new file mode 100644 index 0000000..eb070a7 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 @@ -0,0 +1,121 @@ + +<# +.SYNOPSIS +Retrieves the definition of a Eventstream from a specific workspace in Microsoft Fabric. + +.DESCRIPTION +This function fetches the Eventstream's content or metadata from a workspace. +Handles both synchronous and asynchronous operations, with detailed logging and error handling. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace from which the Eventstream definition is to be retrieved. + +.PARAMETER EventstreamId +(Optional)The unique identifier of the Eventstream whose definition needs to be retrieved. + +.PARAMETER EventstreamFormat +Specifies the format of the Eventstream definition. Currently, only 'ipynb' is supported. +Default: 'ipynb'. + +.EXAMPLE +Get-FabricEventstreamDefinition -WorkspaceId "12345" -EventstreamId "67890" + +Retrieves the definition of the Eventstream with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + +.EXAMPLE +Get-FabricEventstreamDefinition -WorkspaceId "12345" + +Retrieves the definitions of all Eventstreams in the workspace with ID `12345` in the `ipynb` format. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +#> +function Get-FabricEventstreamDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamFormat + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/Eventstreams/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventstreamId + + if ($EventstreamFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $EventstreamFormat + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "Eventstream '$EventstreamId' definition retrieved successfully!" -Level Info + return $response.definition.parts + } + 202 { + + Write-Message -Message "Getting Eventstream '$EventstreamId' definition request accepted. Retrieving in progress!" -Level Debug + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventstream. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Eventstream/New-FabricEventstream.ps1 b/powershell/FabricACEToolkit/Public/Eventstream/New-FabricEventstream.ps1 new file mode 100644 index 0000000..f5def5b --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventstream/New-FabricEventstream.ps1 @@ -0,0 +1,188 @@ +<# +.SYNOPSIS +Creates a new Eventstream in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new Eventstream +in the specified workspace. It supports optional parameters for Eventstream description +and path definitions for the Eventstream content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the Eventstream will be created. + +.PARAMETER EventstreamName +The name of the Eventstream to be created. + +.PARAMETER EventstreamDescription +An optional description for the Eventstream. + +.PARAMETER EventstreamPathDefinition +An optional path to the Eventstream definition file (e.g., .ipynb file) to upload. + +.PARAMETER EventstreamPathPlatformDefinition +An optional path to the platform-specific definition (e.g., .platform file) to upload. + +.EXAMPLE + Add-FabricEventstream -WorkspaceId "workspace-12345" -EventstreamName "New Eventstream" -EventstreamPathDefinition "C:\Eventstreams\example.ipynb" + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricEventstream { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EventstreamName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventstreams" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $EventstreamName + } + + if ($EventstreamDescription) { + $body.description = $EventstreamDescription + } + + if ($EventstreamPathDefinition) { + $EventstreamEncodedContent = Convert-ToBase64 -filePath $EventstreamPathDefinition + + if (-not [string]::IsNullOrEmpty($EventstreamEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "eventstream" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "eventstream.json" + payload = $EventstreamEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in Eventstream definition." -Level Error + return $null + } + } + + if ($EventstreamPathPlatformDefinition) { + $EventstreamEncodedPlatformContent = Convert-ToBase64 -filePath $EventstreamPathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($EventstreamEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "eventstream" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $EventstreamEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Eventstream '$EventstreamName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Eventstream '$EventstreamName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Eventstream. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventstream/Remove-FabricEventstream.ps1 b/powershell/FabricACEToolkit/Public/Eventstream/Remove-FabricEventstream.ps1 new file mode 100644 index 0000000..ef59265 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventstream/Remove-FabricEventstream.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS +Deletes an Eventstream from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricEventstream` function sends a DELETE request to the Fabric API to remove a specified Eventstream from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the Eventstream to delete. + +.PARAMETER EventstreamId +(Mandatory) The ID of the Eventstream to be deleted. + +.EXAMPLE +Remove-FabricEventstream -WorkspaceId "12345" -EventstreamId "67890" + +Deletes the Eventstream with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricEventstream { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventstreams/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventstreamId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Eventstream '$EventstreamId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete Eventstream '$EventstreamId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventstream/Update-FabricEventstream.ps1 b/powershell/FabricACEToolkit/Public/Eventstream/Update-FabricEventstream.ps1 new file mode 100644 index 0000000..28103bf --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventstream/Update-FabricEventstream.ps1 @@ -0,0 +1,107 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric Eventstream. + +.DESCRIPTION +The `Update-FabricEventstream` function updates the name and/or description of a specified Fabric Eventstream by making a PATCH request to the API. + +.PARAMETER EventstreamId +The unique identifier of the Eventstream to be updated. + +.PARAMETER EventstreamName +The new name for the Eventstream. + +.PARAMETER EventstreamDescription +(Optional) The new description for the Eventstream. + +.EXAMPLE +Update-FabricEventstream -EventstreamId "Eventstream123" -EventstreamName "NewEventstreamName" + +Updates the name of the Eventstream with the ID "Eventstream123" to "NewEventstreamName". + +.EXAMPLE +Update-FabricEventstream -EventstreamId "Eventstream123" -EventstreamName "NewName" -EventstreamDescription "Updated description" + +Updates both the name and description of the Eventstream "Eventstream123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricEventstream { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$EventstreamName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventstreams/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventstreamId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $EventstreamName + } + + if ($EventstreamDescription) { + $body.description = $EventstreamDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Eventstream '$EventstreamName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Eventstream. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 b/powershell/FabricACEToolkit/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 new file mode 100644 index 0000000..0929734 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 @@ -0,0 +1,180 @@ +<# +.SYNOPSIS +Updates the definition of a Eventstream in a Microsoft Fabric workspace. + +.DESCRIPTION +This function allows updating the content or metadata of a Eventstream in a Microsoft Fabric workspace. +The Eventstream content can be provided as file paths, and metadata updates can optionally be enabled. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace where the Eventstream resides. + +.PARAMETER EventstreamId +(Mandatory) The unique identifier of the Eventstream to be updated. + +.PARAMETER EventstreamPathDefinition +(Mandatory) The file path to the Eventstream content definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER EventstreamPathPlatformDefinition +(Optional) The file path to the Eventstream's platform-specific definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER UpdateMetadata +(Optional)A boolean flag indicating whether to update the Eventstream's metadata. +Default: `$false`. + +.EXAMPLE +Update-FabricEventstreamDefinition -WorkspaceId "12345" -EventstreamId "67890" -EventstreamPathDefinition "C:\Eventstreams\Eventstream.ipynb" + +Updates the content of the Eventstream with ID `67890` in the workspace `12345` using the specified Eventstream file. + +.EXAMPLE +Update-FabricEventstreamDefinition -WorkspaceId "12345" -EventstreamId "67890" -EventstreamPathDefinition "C:\Eventstreams\Eventstream.ipynb" -UpdateMetadata $true + +Updates both the content and metadata of the Eventstream with ID `67890` in the workspace `12345`. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- The Eventstream content is encoded as Base64 before being sent to the Fabric API. +- This function handles asynchronous operations and retrieves operation results if required. + +Author: Tiago Balabuch + +#> + +function Update-FabricEventstreamDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/eventstreams/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventstreamId + + if($EventstreamPathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + parts = @() + } + } + + if ($EventstreamPathDefinition) { + $EventstreamEncodedContent = Convert-ToBase64 -filePath $EventstreamPathDefinition + + if (-not [string]::IsNullOrEmpty($EventstreamEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "eventstream.json" + payload = $EventstreamEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in Eventstream definition." -Level Error + return $null + } + } + + if ($EventstreamPathPlatformDefinition) { + $EventstreamEncodedPlatformContent = Convert-ToBase64 -filePath $EventstreamPathPlatformDefinition + if (-not [string]::IsNullOrEmpty($EventstreamEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $EventstreamEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for Eventstream '$EventstreamId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for Eventstream '$EventstreamId' accepted. Operation in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Eventstream. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 b/powershell/FabricACEToolkit/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 new file mode 100644 index 0000000..6608729 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 @@ -0,0 +1,155 @@ +<# +.SYNOPSIS +Retrieves an KQLDashboard or a list of KQLDashboards from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricKQLDashboard` function sends a GET request to the Fabric API to retrieve KQLDashboard details for a given workspace. It can filter the results by `KQLDashboardName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query KQLDashboards. + +.PARAMETER KQLDashboardName +(Optional) The name of the specific KQLDashboard to retrieve. + +.EXAMPLE +Get-FabricKQLDashboard -WorkspaceId "12345" -KQLDashboardName "Development" + +Retrieves the "Development" KQLDashboard from workspace "12345". + +.EXAMPLE +Get-FabricKQLDashboard -WorkspaceId "12345" + +Retrieves all KQLDashboards in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricKQLDashboard { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLDashboardName + ) + + try { + # Step 1: Handle ambiguous input + if ($KQLDashboardId -and $KQLDashboardName) { + Write-Message -Message "Both 'KQLDashboardId' and 'KQLDashboardName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $KQLDashboards = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/kqlDashboards" -f $FabricConfig.BaseUrl, $WorkspaceId + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $KQLDashboards += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $KQLDashboard = if ($KQLDashboardId) { + $KQLDashboards | Where-Object { $_.Id -eq $KQLDashboardId } + } + elseif ($KQLDashboardName) { + $KQLDashboards | Where-Object { $_.DisplayName -eq $KQLDashboardName } + } + else { + # Return all KQLDashboards if no filter is provided + Write-Message -Message "No filter provided. Returning all KQLDashboards." -Level Debug + $KQLDashboards + } + + # Step 9: Handle results + if ($KQLDashboard) { + Write-Message -Message "KQLDashboard found matching the specified criteria." -Level Debug + return $KQLDashboard + } + else { + Write-Message -Message "No KQLDashboard found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDashboard. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 b/powershell/FabricACEToolkit/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 new file mode 100644 index 0000000..4f0cf5d --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 @@ -0,0 +1,120 @@ + +<# +.SYNOPSIS +Retrieves the definition of a KQLDashboard from a specific workspace in Microsoft Fabric. + +.DESCRIPTION +This function fetches the KQLDashboard's content or metadata from a workspace. +Handles both synchronous and asynchronous operations, with detailed logging and error handling. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace from which the KQLDashboard definition is to be retrieved. + +.PARAMETER KQLDashboardId +(Optional)The unique identifier of the KQLDashboard whose definition needs to be retrieved. + +.PARAMETER KQLDashboardFormat +Specifies the format of the KQLDashboard definition. + +.EXAMPLE +Get-FabricKQLDashboardDefinition -WorkspaceId "12345" -KQLDashboardId "67890" + +Retrieves the definition of the KQLDashboard with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + +.EXAMPLE +Get-FabricKQLDashboardDefinition -WorkspaceId "12345" + +Retrieves the definitions of all KQLDashboards in the workspace with ID `12345` in the `ipynb` format. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +#> +function Get-FabricKQLDashboardDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardFormat + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDashboards/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDashboardId + + if ($KQLDashboardFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $KQLDashboardFormat + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "KQLDashboard '$KQLDashboardId' definition retrieved successfully!" -Level Debug + return $response.definition.parts + } + 202 { + + Write-Message -Message "Getting KQLDashboard '$KQLDashboardId' definition request accepted. Retrieving in progress!" -Level Debug + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDashboard. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 b/powershell/FabricACEToolkit/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 new file mode 100644 index 0000000..50694d7 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 @@ -0,0 +1,188 @@ +<# +.SYNOPSIS +Creates a new KQLDashboard in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new KQLDashboard +in the specified workspace. It supports optional parameters for KQLDashboard description +and path definitions for the KQLDashboard content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the KQLDashboard will be created. + +.PARAMETER KQLDashboardName +The name of the KQLDashboard to be created. + +.PARAMETER KQLDashboardDescription +An optional description for the KQLDashboard. + +.PARAMETER KQLDashboardPathDefinition +An optional path to the KQLDashboard definition file (e.g., .ipynb file) to upload. + +.PARAMETER KQLDashboardPathPlatformDefinition +An optional path to the platform-specific definition (e.g., .platform file) to upload. + +.EXAMPLE + Add-FabricKQLDashboard -WorkspaceId "workspace-12345" -KQLDashboardName "New KQLDashboard" -KQLDashboardPathDefinition "C:\KQLDashboards\example.ipynb" + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricKQLDashboard { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLDashboardName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDashboards" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $KQLDashboardName + } + + if ($KQLDashboardDescription) { + $body.description = $KQLDashboardDescription + } + + if ($KQLDashboardPathDefinition) { + $KQLDashboardEncodedContent = Convert-ToBase64 -filePath $KQLDashboardPathDefinition + + if (-not [string]::IsNullOrEmpty($KQLDashboardEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "KQLDashboard" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "RealTimeDashboard.json" + payload = $KQLDashboardEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in KQLDashboard definition." -Level Error + return $null + } + } + + if ($KQLDashboardPathPlatformDefinition) { + $KQLDashboardEncodedPlatformContent = Convert-ToBase64 -filePath $KQLDashboardPathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($KQLDashboardEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = $null + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $KQLDashboardEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "KQLDashboard '$KQLDashboardName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "KQLDashboard '$KQLDashboardName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create KQLDashboard. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 b/powershell/FabricACEToolkit/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 new file mode 100644 index 0000000..166e763 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS +Deletes an KQLDashboard from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricKQLDashboard` function sends a DELETE request to the Fabric API to remove a specified KQLDashboard from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the KQLDashboard to delete. + +.PARAMETER KQLDashboardId +(Mandatory) The ID of the KQLDashboard to be deleted. + +.EXAMPLE +Remove-FabricKQLDashboard -WorkspaceId "12345" -KQLDashboardId "67890" + +Deletes the KQLDashboard with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricKQLDashboard { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDashboards/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDashboardId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "KQLDashboard '$KQLDashboardId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete KQLDashboard '$KQLDashboardId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 b/powershell/FabricACEToolkit/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 new file mode 100644 index 0000000..874a614 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 @@ -0,0 +1,107 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric KQLDashboard. + +.DESCRIPTION +The `Update-FabricKQLDashboard` function updates the name and/or description of a specified Fabric KQLDashboard by making a PATCH request to the API. + +.PARAMETER KQLDashboardId +The unique identifier of the KQLDashboard to be updated. + +.PARAMETER KQLDashboardName +The new name for the KQLDashboard. + +.PARAMETER KQLDashboardDescription +(Optional) The new description for the KQLDashboard. + +.EXAMPLE +Update-FabricKQLDashboard -KQLDashboardId "KQLDashboard123" -KQLDashboardName "NewKQLDashboardName" + +Updates the name of the KQLDashboard with the ID "KQLDashboard123" to "NewKQLDashboardName". + +.EXAMPLE +Update-FabricKQLDashboard -KQLDashboardId "KQLDashboard123" -KQLDashboardName "NewName" -KQLDashboardDescription "Updated description" + +Updates both the name and description of the KQLDashboard "KQLDashboard123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricKQLDashboard { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLDashboardName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDashboards/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDashboardId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $KQLDashboardName + } + + if ($KQLDashboardDescription) { + $body.description = $KQLDashboardDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "KQLDashboard '$KQLDashboardName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update KQLDashboard. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 b/powershell/FabricACEToolkit/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 new file mode 100644 index 0000000..14b423f --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 @@ -0,0 +1,166 @@ +<# +.SYNOPSIS +Updates the definition of a KQLDashboard in a Microsoft Fabric workspace. + +.DESCRIPTION +This function allows updating the content or metadata of a KQLDashboard in a Microsoft Fabric workspace. +The KQLDashboard content can be provided as file paths, and metadata updates can optionally be enabled. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace where the KQLDashboard resides. + +.PARAMETER KQLDashboardId +(Mandatory) The unique identifier of the KQLDashboard to be updated. + +.PARAMETER KQLDashboardPathDefinition +(Mandatory) The file path to the KQLDashboard content definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER KQLDashboardPathPlatformDefinition +(Optional) The file path to the KQLDashboard's platform-specific definition file. The content will be encoded as Base64 and sent in the request. + + +.EXAMPLE +Update-FabricKQLDashboardDefinition -WorkspaceId "12345" -KQLDashboardId "67890" -KQLDashboardPathDefinition "C:\KQLDashboards\KQLDashboard.ipynb" + +Updates the content of the KQLDashboard with ID `67890` in the workspace `12345` using the specified KQLDashboard file. + +.EXAMPLE +Update-FabricKQLDashboardDefinition -WorkspaceId "12345" -KQLDashboardId "67890" -KQLDashboardPathDefinition "C:\KQLDashboards\KQLDashboard.ipynb" + +Updates both the content and metadata of the KQLDashboard with ID `67890` in the workspace `12345`. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- The KQLDashboard content is encoded as Base64 before being sent to the Fabric API. +- This function handles asynchronous operations and retrieves operation results if required. + +Author: Tiago Balabuch + +#> + +function Update-FabricKQLDashboardDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/KQLDashboards/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDashboardId + + if($KQLDashboardPathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + format = $null + parts = @() + } + } + + if ($KQLDashboardPathDefinition) { + $KQLDashboardEncodedContent = Convert-ToBase64 -filePath $KQLDashboardPathDefinition + + if (-not [string]::IsNullOrEmpty($KQLDashboardEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "RealTimeDashboard.json" + payload = $KQLDashboardEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in KQLDashboard definition." -Level Error + return $null + } + } + + if ($KQLDashboardPathPlatformDefinition) { + $KQLDashboardEncodedPlatformContent = Convert-ToBase64 -filePath $KQLDashboardPathPlatformDefinition + if (-not [string]::IsNullOrEmpty($KQLDashboardEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $KQLDashboardEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for KQLDashboard '$KQLDashboardId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for KQLDashboard '$KQLDashboardId' accepted. Operation in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + $operationResult = Get-FabricLongRunningOperation -operationId $operationId + + # Handle operation result + if ($operationResult.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + + $result = Get-FabricLongRunningOperationResult -operationId $operationId + return $result.definition.parts + } + else { + Write-Message -Message "Operation Failed" -Level Debug + return $operationResult.definition.parts + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update KQLDashboard. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Database/Get-FabricKQLDatabase.ps1 b/powershell/FabricACEToolkit/Public/KQL Database/Get-FabricKQLDatabase.ps1 new file mode 100644 index 0000000..94677fe --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Database/Get-FabricKQLDatabase.ps1 @@ -0,0 +1,153 @@ +<# +.SYNOPSIS +Retrieves an KQLDatabase or a list of KQLDatabases from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricKQLDatabase` function sends a GET request to the Fabric API to retrieve KQLDatabase details for a given workspace. It can filter the results by `KQLDatabaseName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query KQLDatabases. + +.PARAMETER KQLDatabaseName +(Optional) The name of the specific KQLDatabase to retrieve. + +.EXAMPLE +Get-FabricKQLDatabase -WorkspaceId "12345" -KQLDatabaseName "Development" + +Retrieves the "Development" KQLDatabase from workspace "12345". + +.EXAMPLE +Get-FabricKQLDatabase -WorkspaceId "12345" + +Retrieves all KQLDatabases in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> +function Get-FabricKQLDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLDatabaseName + ) + + try { + # Step 1: Handle ambiguous input + if ($KQLDatabaseId -and $KQLDatabaseName) { + Write-Message -Message "Both 'KQLDatabaseId' and 'KQLDatabaseName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $KQLDatabases = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases" -f $FabricConfig.BaseUrl, $WorkspaceId + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $KQLDatabases += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $KQLDatabase = if ($KQLDatabaseId) { + $KQLDatabases | Where-Object { $_.Id -eq $KQLDatabaseId } + } + elseif ($KQLDatabaseName) { + $KQLDatabases | Where-Object { $_.DisplayName -eq $KQLDatabaseName } + } + else { + # Return all KQLDatabases if no filter is provided + Write-Message -Message "No filter provided. Returning all KQLDatabases." -Level Debug + $KQLDatabases + } + + # Step 9: Handle results + if ($KQLDatabase) { + Write-Message -Message "KQLDatabase found matching the specified criteria." -Level Debug + return $KQLDatabase + } + else { + Write-Message -Message "No KQLDatabase found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 b/powershell/FabricACEToolkit/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 new file mode 100644 index 0000000..a3d5611 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 @@ -0,0 +1,129 @@ + +<# +.SYNOPSIS +Retrieves the definition of a KQLDatabase from a specific workspace in Microsoft Fabric. + +.DESCRIPTION +This function fetches the KQLDatabase's content or metadata from a workspace. +It supports retrieving KQLDatabase definitions in the Jupyter KQLDatabase (`ipynb`) format. +Handles both synchronous and asynchronous operations, with detailed logging and error handling. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace from which the KQLDatabase definition is to be retrieved. + +.PARAMETER KQLDatabaseId +(Optional)The unique identifier of the KQLDatabase whose definition needs to be retrieved. + +.PARAMETER KQLDatabaseFormat +Specifies the format of the KQLDatabase definition. Currently, only 'ipynb' is supported. + + +.EXAMPLE +Get-FabricKQLDatabaseDefinition -WorkspaceId "12345" -KQLDatabaseId "67890" + +Retrieves the definition of the KQLDatabase with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + +.EXAMPLE +Get-FabricKQLDatabaseDefinition -WorkspaceId "12345" + +Retrieves the definitions of all KQLDatabases in the workspace with ID `12345` in the `ipynb` format. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +#> +function Get-FabricKQLDatabaseDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseFormat + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/KQLDatabases/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDatabaseId + + if ($KQLDatabaseFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $KQLDatabaseFormat + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "KQLDatabase '$KQLDatabaseId' definition retrieved successfully!" -Level Debug + return $response + } + 202 { + + Write-Message -Message "Getting KQLDatabase '$KQLDatabaseId' definition request accepted. Retrieving in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Database/New-FabricKQLDatabase.ps1 b/powershell/FabricACEToolkit/Public/KQL Database/New-FabricKQLDatabase.ps1 new file mode 100644 index 0000000..2109887 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Database/New-FabricKQLDatabase.ps1 @@ -0,0 +1,288 @@ +<# +.SYNOPSIS +Creates a new KQLDatabase in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new KQLDatabase +in the specified workspace. It supports optional parameters for KQLDatabase description +and path definitions for the KQLDatabase content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the KQLDatabase will be created. + +.PARAMETER KQLDatabaseName +The name of the KQLDatabase to be created. + +.PARAMETER KQLDatabaseDescription +An optional description for the KQLDatabase. + +.PARAMETER KQLDatabasePathDefinition +An optional path to the KQLDatabase definition file (e.g., .ipynb file) to upload. + +.PARAMETER KQLDatabasePathPlatformDefinition +An optional path to the platform-specific definition (e.g., .platform file) to upload. + +.EXAMPLE + Add-FabricKQLDatabase -WorkspaceId "workspace-12345" -KQLDatabaseName "New KQLDatabase" -KQLDatabasePathDefinition "C:\KQLDatabases\example.ipynb" + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Precedent Request Body + - Definition file high priority. + - CreationPayload is evaluate only if Definition file is not provided. + - invitationToken has priority over all other payload fields. + +Author: Tiago Balabuch + +#> + +function New-FabricKQLDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLDatabaseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$parentEventhouseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet("ReadWrite", "Shortcut")] + [string]$KQLDatabaseType, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLInvitationToken, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLSourceClusterUri, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLSourceDatabaseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabasePathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabasePathPlatformDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabasePathSchemaDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body ### This is working + $body = @{ + displayName = $KQLDatabaseName + } + + if ($KQLDatabaseDescription) { + $body.description = $KQLDatabaseDescription + } + + if ($KQLDatabasePathDefinition) { + $KQLDatabaseEncodedContent = Convert-ToBase64 -filePath $KQLDatabasePathDefinition + + $body.definition = @{ + parts = @() + } + + if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedContent)) { + + + # Add new part to the parts array + $body.definition.parts += @{ + path = "DatabaseProperties.json" + payload = $KQLDatabaseEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in KQLDatabase definition." -Level Error + return $null + } + + if ($KQLDatabasePathPlatformDefinition) { + $KQLDatabaseEncodedPlatformContent = Convert-ToBase64 -filePath $KQLDatabasePathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedPlatformContent)) { + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $KQLDatabaseEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + + } + if ($KQLDatabasePathSchemaDefinition) { + $KQLDatabaseEncodedSchemaContent = Convert-ToBase64 -filePath $KQLDatabasePathSchemaDefinition + + if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedSchemaContent)) { + + # Add new part to the parts array + $body.definition.parts += @{ + path = "DatabaseSchema.kql" + payload = $KQLDatabaseEncodedSchemaContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in schema definition." -Level Error + return $null + } + } + + } + else { + if ($KQLDatabaseType -eq "Shortcut") { + if (-not $parentEventhouseId) { + Write-Message -Message "Error: 'parentEventhouseId' is required for Shortcut type." -Level Error + return $null + } + if (-not ($KQLInvitationToken -or $KQLSourceClusterUri -or $KQLSourceDatabaseName)) { + Write-Message -Message "Error: Provide either 'KQLInvitationToken', 'KQLSourceClusterUri', or 'KQLSourceDatabaseName'." -Level Error + return $null + } + if ($KQLInvitationToken) { + Write-Message -Message "Info: 'KQLInvitationToken' is provided." -Level Warning + + if ($KQLSourceClusterUri) { + Write-Message -Message "Warning: 'KQLSourceClusterUri' is ignored when 'KQLInvitationToken' is provided." -Level Warning + #$KQLSourceClusterUri = $null + } + if ($KQLSourceDatabaseName) { + Write-Message -Message "Warning: 'KQLSourceDatabaseName' is ignored when 'KQLInvitationToken' is provided." -Level Warning + #$KQLSourceDatabaseName = $null + } + } + if ($KQLSourceClusterUri -and -not $KQLSourceDatabaseName) { + Write-Message -Message "Error: 'KQLSourceDatabaseName' is required when 'KQLSourceClusterUri' is provided." -Level Error + return $null + } + } + + # Validate ReadWrite type database + if ($KQLDatabaseType -eq "ReadWrite" -and -not $parentEventhouseId) { + Write-Message -Message "Error: 'parentEventhouseId' is required for ReadWrite type." -Level Error + return $null + } + + $body.creationPayload = @{ + databaseType = $KQLDatabaseType + parentEventhouseItemId = $parentEventhouseId + } + + if ($KQLDatabaseType -eq "Shortcut") { + if ($KQLInvitationToken) { + + $body.creationPayload.invitationToken = $KQLInvitationToken + } + if ($KQLSourceClusterUri -and -not $KQLInvitationToken) { + $body.creationPayload.sourceClusterUri = $KQLSourceClusterUri + } + if ($KQLSourceDatabaseName -and -not $KQLInvitationToken) { + $body.creationPayload.sourceDatabaseName = $KQLSourceDatabaseName + } + } + + + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "KQLDatabase '$KQLDatabaseName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "KQLDatabase '$KQLDatabaseName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation result: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create KQLDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Database/Remove-FabricKQLDatabase.ps1 b/powershell/FabricACEToolkit/Public/KQL Database/Remove-FabricKQLDatabase.ps1 new file mode 100644 index 0000000..2b5d69f --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Database/Remove-FabricKQLDatabase.ps1 @@ -0,0 +1,74 @@ +<# +.SYNOPSIS +Deletes an KQLDatabase from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricKQLDatabase` function sends a DELETE request to the Fabric API to remove a specified KQLDatabase from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the KQLDatabase to delete. + +.PARAMETER KQLDatabaseId +(Mandatory) The ID of the KQLDatabase to be deleted. + +.EXAMPLE +Remove-FabricKQLDatabase -WorkspaceId "12345" -KQLDatabaseId "67890" + +Deletes the KQLDatabase with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricKQLDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "KQLDatabase '$KQLDatabaseId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete KQLDatabase '$KQLDatabaseId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Database/Update-FabricKQLDatabase.ps1 b/powershell/FabricACEToolkit/Public/KQL Database/Update-FabricKQLDatabase.ps1 new file mode 100644 index 0000000..4c15f3a --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Database/Update-FabricKQLDatabase.ps1 @@ -0,0 +1,108 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric KQLDatabase. + +.DESCRIPTION +The `Update-FabricKQLDatabase` function updates the name and/or description of a specified Fabric KQLDatabase by making a PATCH request to the API. + +.PARAMETER KQLDatabaseId +The unique identifier of the KQLDatabase to be updated. + +.PARAMETER KQLDatabaseName +The new name for the KQLDatabase. + +.PARAMETER KQLDatabaseDescription +(Optional) The new description for the KQLDatabase. + +.EXAMPLE +Update-FabricKQLDatabase -KQLDatabaseId "KQLDatabase123" -KQLDatabaseName "NewKQLDatabaseName" + +Updates the name of the KQLDatabase with the ID "KQLDatabase123" to "NewKQLDatabaseName". + +.EXAMPLE +Update-FabricKQLDatabase -KQLDatabaseId "KQLDatabase123" -KQLDatabaseName "NewName" -KQLDatabaseDescription "Updated description" + +Updates both the name and description of the KQLDatabase "KQLDatabase123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricKQLDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLDatabaseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $KQLDatabaseName + } + + if ($KQLDatabaseDescription) { + $body.description = $KQLDatabaseDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "KQLDatabase '$KQLDatabaseName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update KQLDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 b/powershell/FabricACEToolkit/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 new file mode 100644 index 0000000..35df15f --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 @@ -0,0 +1,202 @@ +<# +.SYNOPSIS +Updates the definition of a KQLDatabase in a Microsoft Fabric workspace. + +.DESCRIPTION +This function allows updating the content or metadata of a KQLDatabase in a Microsoft Fabric workspace. +The KQLDatabase content can be provided as file paths, and metadata updates can optionally be enabled. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace where the KQLDatabase resides. + +.PARAMETER KQLDatabaseId +(Mandatory) The unique identifier of the KQLDatabase to be updated. + +.PARAMETER KQLDatabasePathDefinition +(Mandatory) The file path to the KQLDatabase content definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER KQLDatabasePathPlatformDefinition +(Optional) The file path to the KQLDatabase's platform-specific definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER UpdateMetadata +(Optional)A boolean flag indicating whether to update the KQLDatabase's metadata. +Default: `$false`. + +.EXAMPLE +Update-FabricKQLDatabaseDefinition -WorkspaceId "12345" -KQLDatabaseId "67890" -KQLDatabasePathDefinition "C:\KQLDatabases\KQLDatabase.ipynb" + +Updates the content of the KQLDatabase with ID `67890` in the workspace `12345` using the specified KQLDatabase file. + +.EXAMPLE +Update-FabricKQLDatabaseDefinition -WorkspaceId "12345" -KQLDatabaseId "67890" -KQLDatabasePathDefinition "C:\KQLDatabases\KQLDatabase.ipynb" -UpdateMetadata $true + +Updates both the content and metadata of the KQLDatabase with ID `67890` in the workspace `12345`. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- The KQLDatabase content is encoded as Base64 before being sent to the Fabric API. +- This function handles asynchronous operations and retrieves operation results if required. + +Author: Tiago Balabuch + +#> + +function Update-FabricKQLDatabaseDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabasePathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabasePathPlatformDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabasePathSchemaDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDatabaseId + + if($KQLDatabasePathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + parts = @() + } + } + + if ($KQLDatabasePathDefinition) { + $KQLDatabaseEncodedContent = Convert-ToBase64 -filePath $KQLDatabasePathDefinition + + if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "DatabaseProperties.json" + payload = $KQLDatabaseEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in KQLDatabase definition." -Level Error + return $null + } + } + + if ($KQLDatabasePathPlatformDefinition) { + $KQLDatabaseEncodedPlatformContent = Convert-ToBase64 -filePath $KQLDatabasePathPlatformDefinition + if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $KQLDatabaseEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + if ($KQLDatabasePathSchemaDefinition) { + $KQLDatabaseEncodedSchemaContent = Convert-ToBase64 -filePath $KQLDatabasePathSchemaDefinition + + if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedSchemaContent)) { + + # Add new part to the parts array + $body.definition.parts += @{ + path = "DatabaseSchema.kql" + payload = $KQLDatabaseEncodedSchemaContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in schema definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for KQLDatabase '$KQLDatabaseId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for KQLDatabase '$KQLDatabaseId' accepted. Operation in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + Write-Message -Message "Operation completed successfully." -Level Info + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update KQLDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 b/powershell/FabricACEToolkit/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 new file mode 100644 index 0000000..b1c06d8 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 @@ -0,0 +1,154 @@ +<# +.SYNOPSIS +Retrieves an KQLQueryset or a list of KQLQuerysets from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricKQLQueryset` function sends a GET request to the Fabric API to retrieve KQLQueryset details for a given workspace. It can filter the results by `KQLQuerysetName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query KQLQuerysets. + +.PARAMETER KQLQuerysetName +(Optional) The name of the specific KQLQueryset to retrieve. + +.EXAMPLE +Get-FabricKQLQueryset -WorkspaceId "12345" -KQLQuerysetName "Development" + +Retrieves the "Development" KQLQueryset from workspace "12345". + +.EXAMPLE +Get-FabricKQLQueryset -WorkspaceId "12345" + +Retrieves all KQLQuerysets in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricKQLQueryset { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLQuerysetName + ) + + try { + # Step 1: Handle ambiguous input + if ($KQLQuerysetId -and $KQLQuerysetName) { + Write-Message -Message "Both 'KQLQuerysetId' and 'KQLQuerysetName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $KQLQuerysets = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets" -f $FabricConfig.BaseUrl, $WorkspaceId + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $KQLQuerysets += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $KQLQueryset = if ($KQLQuerysetId) { + $KQLQuerysets | Where-Object { $_.Id -eq $KQLQuerysetId } + } + elseif ($KQLQuerysetName) { + $KQLQuerysets | Where-Object { $_.DisplayName -eq $KQLQuerysetName } + } + else { + # Return all KQLQuerysets if no filter is provided + Write-Message -Message "No filter provided. Returning all KQLQuerysets." -Level Debug + $KQLQuerysets + } + + # Step 9: Handle results + if ($KQLQueryset) { + Write-Message -Message "KQLQueryset found matching the specified criteria." -Level Debug + return $KQLQueryset + } + else { + Write-Message -Message "No KQLQueryset found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLQueryset. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 b/powershell/FabricACEToolkit/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 new file mode 100644 index 0000000..79e8819 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 @@ -0,0 +1,120 @@ + +<# +.SYNOPSIS +Retrieves the definition of a KQLQueryset from a specific workspace in Microsoft Fabric. + +.DESCRIPTION +This function fetches the KQLQueryset's content or metadata from a workspace. +Handles both synchronous and asynchronous operations, with detailed logging and error handling. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace from which the KQLQueryset definition is to be retrieved. + +.PARAMETER KQLQuerysetId +(Optional)The unique identifier of the KQLQueryset whose definition needs to be retrieved. + +.PARAMETER KQLQuerysetFormat +Specifies the format of the KQLQueryset definition. + +.EXAMPLE +Get-FabricKQLQuerysetDefinition -WorkspaceId "12345" -KQLQuerysetId "67890" + +Retrieves the definition of the KQLQueryset with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + +.EXAMPLE +Get-FabricKQLQuerysetDefinition -WorkspaceId "12345" + +Retrieves the definitions of all KQLQuerysets in the workspace with ID `12345` in the `ipynb` format. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +#> +function Get-FabricKQLQuerysetDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetFormat + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLQuerysetId + + if ($KQLQuerysetFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $KQLQuerysetFormat + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "KQLQueryset '$KQLQuerysetId' definition retrieved successfully!" -Level Debug + return $response.definition.parts + } + 202 { + + Write-Message -Message "Getting KQLQueryset '$KQLQuerysetId' definition request accepted. Retrieving in progress!" -Level Debug + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLQueryset. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/KQL Queryset/New-FabricKQLQueryset.ps1 b/powershell/FabricACEToolkit/Public/KQL Queryset/New-FabricKQLQueryset.ps1 new file mode 100644 index 0000000..fea1665 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Queryset/New-FabricKQLQueryset.ps1 @@ -0,0 +1,188 @@ +<# +.SYNOPSIS +Creates a new KQLQueryset in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new KQLQueryset +in the specified workspace. It supports optional parameters for KQLQueryset description +and path definitions for the KQLQueryset content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the KQLQueryset will be created. + +.PARAMETER KQLQuerysetName +The name of the KQLQueryset to be created. + +.PARAMETER KQLQuerysetDescription +An optional description for the KQLQueryset. + +.PARAMETER KQLQuerysetPathDefinition +An optional path to the KQLQueryset definition file (e.g., .ipynb file) to upload. + +.PARAMETER KQLQuerysetPathPlatformDefinition +An optional path to the platform-specific definition (e.g., .platform file) to upload. + +.EXAMPLE + Add-FabricKQLQueryset -WorkspaceId "workspace-12345" -KQLQuerysetName "New KQLQueryset" -KQLQuerysetPathDefinition "C:\KQLQuerysets\example.ipynb" + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricKQLQueryset { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLQuerysetName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $KQLQuerysetName + } + + if ($KQLQuerysetDescription) { + $body.description = $KQLQuerysetDescription + } + + if ($KQLQuerysetPathDefinition) { + $KQLQuerysetEncodedContent = Convert-ToBase64 -filePath $KQLQuerysetPathDefinition + + if (-not [string]::IsNullOrEmpty($KQLQuerysetEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = $null + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "RealTimeQueryset.json" + payload = $KQLQuerysetEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in KQLQueryset definition." -Level Error + return $null + } + } + + if ($KQLQuerysetPathPlatformDefinition) { + $KQLQuerysetEncodedPlatformContent = Convert-ToBase64 -filePath $KQLQuerysetPathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($KQLQuerysetEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = $null + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $KQLQuerysetEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "KQLQueryset '$KQLQuerysetName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "KQLQueryset '$KQLQuerysetName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create KQLQueryset. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 b/powershell/FabricACEToolkit/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 new file mode 100644 index 0000000..d9a48c5 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS +Deletes an KQLQueryset from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricKQLQueryset` function sends a DELETE request to the Fabric API to remove a specified KQLQueryset from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the KQLQueryset to delete. + +.PARAMETER KQLQuerysetId +(Mandatory) The ID of the KQLQueryset to be deleted. + +.EXAMPLE +Remove-FabricKQLQueryset -WorkspaceId "12345" -KQLQuerysetId "67890" + +Deletes the KQLQueryset with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricKQLQueryset { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLQuerysetId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "KQLQueryset '$KQLQuerysetId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete KQLQueryset '$KQLQuerysetId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 b/powershell/FabricACEToolkit/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 new file mode 100644 index 0000000..4377448 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 @@ -0,0 +1,107 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric KQLQueryset. + +.DESCRIPTION +The `Update-FabricKQLQueryset` function updates the name and/or description of a specified Fabric KQLQueryset by making a PATCH request to the API. + +.PARAMETER KQLQuerysetId +The unique identifier of the KQLQueryset to be updated. + +.PARAMETER KQLQuerysetName +The new name for the KQLQueryset. + +.PARAMETER KQLQuerysetDescription +(Optional) The new description for the KQLQueryset. + +.EXAMPLE +Update-FabricKQLQueryset -KQLQuerysetId "KQLQueryset123" -KQLQuerysetName "NewKQLQuerysetName" + +Updates the name of the KQLQueryset with the ID "KQLQueryset123" to "NewKQLQuerysetName". + +.EXAMPLE +Update-FabricKQLQueryset -KQLQuerysetId "KQLQueryset123" -KQLQuerysetName "NewName" -KQLQuerysetDescription "Updated description" + +Updates both the name and description of the KQLQueryset "KQLQueryset123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricKQLQueryset { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$KQLQuerysetName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLQuerysetId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $KQLQuerysetName + } + + if ($KQLQuerysetDescription) { + $body.description = $KQLQuerysetDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "KQLQueryset '$KQLQuerysetName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update KQLQueryset. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 b/powershell/FabricACEToolkit/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 new file mode 100644 index 0000000..6189f65 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 @@ -0,0 +1,166 @@ +<# +.SYNOPSIS +Updates the definition of a KQLQueryset in a Microsoft Fabric workspace. + +.DESCRIPTION +This function allows updating the content or metadata of a KQLQueryset in a Microsoft Fabric workspace. +The KQLQueryset content can be provided as file paths, and metadata updates can optionally be enabled. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace where the KQLQueryset resides. + +.PARAMETER KQLQuerysetId +(Mandatory) The unique identifier of the KQLQueryset to be updated. + +.PARAMETER KQLQuerysetPathDefinition +(Mandatory) The file path to the KQLQueryset content definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER KQLQuerysetPathPlatformDefinition +(Optional) The file path to the KQLQueryset's platform-specific definition file. The content will be encoded as Base64 and sent in the request. + + +.EXAMPLE +Update-FabricKQLQuerysetDefinition -WorkspaceId "12345" -KQLQuerysetId "67890" -KQLQuerysetPathDefinition "C:\KQLQuerysets\KQLQueryset.ipynb" + +Updates the content of the KQLQueryset with ID `67890` in the workspace `12345` using the specified KQLQueryset file. + +.EXAMPLE +Update-FabricKQLQuerysetDefinition -WorkspaceId "12345" -KQLQuerysetId "67890" -KQLQuerysetPathDefinition "C:\KQLQuerysets\KQLQueryset.ipynb" + +Updates both the content and metadata of the KQLQueryset with ID `67890` in the workspace `12345`. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- The KQLQueryset content is encoded as Base64 before being sent to the Fabric API. +- This function handles asynchronous operations and retrieves operation results if required. + +Author: Tiago Balabuch + +#> + +function Update-FabricKQLQuerysetDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLQuerysetId + + if($KQLQuerysetPathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + format = $null + parts = @() + } + } + + if ($KQLQuerysetPathDefinition) { + $KQLQuerysetEncodedContent = Convert-ToBase64 -filePath $KQLQuerysetPathDefinition + + if (-not [string]::IsNullOrEmpty($KQLQuerysetEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "RealTimeQueryset.json" + payload = $KQLQuerysetEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in KQLQueryset definition." -Level Error + return $null + } + } + + if ($KQLQuerysetPathPlatformDefinition) { + $KQLQuerysetEncodedPlatformContent = Convert-ToBase64 -filePath $KQLQuerysetPathPlatformDefinition + if (-not [string]::IsNullOrEmpty($KQLQuerysetEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $KQLQuerysetEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for KQLQueryset '$KQLQuerysetId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for KQLQueryset '$KQLQuerysetId' accepted. Operation in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + $operationResult = Get-FabricLongRunningOperation -operationId $operationId + + # Handle operation result + if ($operationResult.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + + $result = Get-FabricLongRunningOperationResult -operationId $operationId + return $result.definition.parts + } + else { + Write-Message -Message "Operation Failed" -Level Debug + return $operationResult.definition.parts + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update KQLQueryset. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Lakehouse/Get-FabricLakehouse.ps1 b/powershell/FabricACEToolkit/Public/Lakehouse/Get-FabricLakehouse.ps1 new file mode 100644 index 0000000..ecdeb17 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Lakehouse/Get-FabricLakehouse.ps1 @@ -0,0 +1,154 @@ +<# +.SYNOPSIS +Retrieves an Lakehouse or a list of Lakehouses from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricLakehouse` function sends a GET request to the Fabric API to retrieve Lakehouse details for a given workspace. It can filter the results by `LakehouseName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query Lakehouses. + +.PARAMETER LakehouseName +(Optional) The name of the specific Lakehouse to retrieve. + +.EXAMPLE +Get-FabricLakehouse -WorkspaceId "12345" -LakehouseName "Development" + +Retrieves the "Development" Lakehouse from workspace "12345". + +.EXAMPLE +Get-FabricLakehouse -WorkspaceId "12345" + +Retrieves all Lakehouses in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricLakehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$LakehouseName + ) + + try { + # Step 1: Handle ambiguous input + if ($LakehouseId -and $LakehouseName) { + Write-Message -Message "Both 'LakehouseId' and 'LakehouseName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $lakehouses = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/lakehouses" -f $FabricConfig.BaseUrl, $WorkspaceId + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $lakehouses += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $lakehouse = if ($LakehouseId) { + $lakehouses | Where-Object { $_.Id -eq $LakehouseId } + } + elseif ($LakehouseName) { + $lakehouses | Where-Object { $_.DisplayName -eq $LakehouseName } + } + else { + # Return all lakehouses if no filter is provided + Write-Message -Message "No filter provided. Returning all Lakehouses." -Level Debug + $lakehouses + } + + # Step 9: Handle results + if ($Lakehouse) { + Write-Message -Message "Lakehouse found matching the specified criteria." -Level Debug + return $Lakehouse + } + else { + Write-Message -Message "No Lakehouse found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Lakehouse. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Lakehouse/Get-FabricLakehouseTable.ps1 b/powershell/FabricACEToolkit/Public/Lakehouse/Get-FabricLakehouseTable.ps1 new file mode 100644 index 0000000..e35ce0d --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Lakehouse/Get-FabricLakehouseTable.ps1 @@ -0,0 +1,104 @@ + + +function Get-FabricLakehouseTable { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + + + # Step 2: Initialize variables + $continuationToken = $null + $tables = @() + $maxResults = 100 + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + $baseApiEndpointUrl = "{0}/workspaces/{1}/lakehouses/{2}/tables?maxResults={3}" -f $FabricConfig.BaseUrl, $WorkspaceId, $LakehouseId, $maxResults + + # Step 3: Loop to retrieve data with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + do { + # Step 4: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}&continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 5: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "API response code: $statusCode" -Level Debug + # Step 6: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 7: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $tables += $response.data + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + # Step 9: Handle results + if ($tables) { + Write-Message -Message "Tables found in the Lakehouse '$LakehouseId'." -Level Debug + return $tables + } + else { + Write-Message -Message "No tables found matching in the Lakehouse '$LakehouseId'." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Lakehouse. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Lakehouse/Load-FabricLakehouseTable.ps1 b/powershell/FabricACEToolkit/Public/Lakehouse/Load-FabricLakehouseTable.ps1 new file mode 100644 index 0000000..b1ca082 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Lakehouse/Load-FabricLakehouseTable.ps1 @@ -0,0 +1,139 @@ +function Load-FabricLakehouseTable { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_]*$')] + [string]$TableName, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('File', 'Folder')] + [string]$PathType, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$RelativePath, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('CSV', 'Parquet')] + [string]$FileFormat, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$CsvDelimiter = ",", + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$CsvHeader = $false, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('append', 'overwrite')] + [string]$Mode = "append", + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$Recursive = $false + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/lakehouses/{2}/tables/{3}/load" -f $FabricConfig.BaseUrl, $WorkspaceId, $LakehouseId, $TableName + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + relativePath = $RelativePath + pathType = $PathType + mode = $Mode + recursive = $Recursive + formatOptions = @{ + format = $FileFormat + } + } + + if ($FileFormat -eq "CSV") { + $body.formatOptions.delimiter = $CsvDelimiter + $body.formatOptions.hasHeader = $CsvHeader + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 202) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 5: Handle and log the response + switch ($statusCode) { + 202 { + Write-Message -Message "Load table '$TableName' request accepted. Load table operation in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Load table '$TableName' operation complete successfully!" -Level Info + return $operationStatus + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + throw "API request failed with status code $statusCode." + } + } + + # Step 6: Handle results + + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Lakehouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Lakehouse/New-FabricLakehouse.ps1 b/powershell/FabricACEToolkit/Public/Lakehouse/New-FabricLakehouse.ps1 new file mode 100644 index 0000000..f24c8fe --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Lakehouse/New-FabricLakehouse.ps1 @@ -0,0 +1,136 @@ +<# +.SYNOPSIS +Creates a new Lakehouse in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new Lakehouse +in the specified workspace. It supports optional parameters for Lakehouse description +and path definitions for the Lakehouse content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the Lakehouse will be created. + +.PARAMETER LakehouseName +The name of the Lakehouse to be created. + +.PARAMETER LakehouseDescription +An optional description for the Lakehouse. + +.PARAMETER LakehouseEnableSchemas +An optional path to enable schemas in the Lakehouse + +.EXAMPLE + Add-FabricLakehouse -WorkspaceId "workspace-12345" -LakehouseName "New Lakehouse" -LakehouseEnableSchemas $true + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricLakehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_]*$')] + [string]$LakehouseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$LakehouseEnableSchemas = $false + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/lakehouses" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $LakehouseName + } + + if ($LakehouseDescription) { + $body.description = $LakehouseDescription + } + + if ($true -eq $LakehouseEnableSchemas) { + $body.creationPayload = @{ + enableSchemas = $LakehouseEnableSchemas + } + } + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Lakehouse '$LakehouseName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Lakehouse '$LakehouseName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Lakehouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Lakehouse/Remove-FabricLakehouse.ps1 b/powershell/FabricACEToolkit/Public/Lakehouse/Remove-FabricLakehouse.ps1 new file mode 100644 index 0000000..254bdde --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Lakehouse/Remove-FabricLakehouse.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS +Deletes an Lakehouse from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricLakehouse` function sends a DELETE request to the Fabric API to remove a specified Lakehouse from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the Lakehouse to delete. + +.PARAMETER LakehouseId +(Mandatory) The ID of the Lakehouse to be deleted. + +.EXAMPLE +Remove-FabricLakehouse -WorkspaceId "12345" -LakehouseId "67890" + +Deletes the Lakehouse with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricLakehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/lakehouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $LakehouseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Lakehouse '$LakehouseId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete Lakehouse '$LakehouseId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 b/powershell/FabricACEToolkit/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 new file mode 100644 index 0000000..c680beb --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 @@ -0,0 +1,160 @@ +function Start-FabricLakehouseTableMaintenance { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('TableMaintenance')] + [string]$JobType = "TableMaintenance", + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SchemaName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$TableName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$IsVOrder, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [array]$ColumnsZOrderBy, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern("^\d+:[0-1][0-9]|2[0-3]:[0-5][0-9]:[0-5][0-9]$")] + [string]$retentionPeriod, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$waitForCompletion = $false + + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + + $lakehouse = Get-FabricLakehouse -WorkspaceId $WorkspaceId -LakehouseId $LakehouseId + if ($lakehouse.properties.PSObject.Properties['defaultSchema'] -and -not $SchemaName) { + Write-Error "The Lakehouse '$lakehouse.displayName' has schema enabled, but no schema name was provided. Please specify the 'SchemaName' parameter to proceed." + return + } + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/lakehouses/{2}/jobs/instances?jobType={3}" -f $FabricConfig.BaseUrl, $WorkspaceId , $LakehouseId, $JobType + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + executionData = @{ + tableName = $TableName + optimizeSettings = @{} + } + } + if ($lakehouse.properties.PSObject.Properties['defaultSchema'] -and $SchemaName) { + $body.executionData.schemaName = $SchemaName + } + + if ($IsVOrder) { + $body.executionData.optimizeSettings.vOrder = $IsVOrder + } + + if ($ColumnsZOrderBy) { + # Ensure $ColumnsZOrderBy is an array + if (-not ($ColumnsZOrderBy -is [array])) { + $ColumnsZOrderBy = $ColumnsZOrderBy -split "," + } + # Add it to the optimizeSettings in the request body + $body.executionData.optimizeSettings.zOrderBy = $ColumnsZOrderBy + } + + + + if ($retentionPeriod) { + + if (-not $body.executionData.PSObject.Properties['vacuumSettings']) { + $body.executionData.vacuumSettings = @{ + retentionPeriod = @() + } + } + $body.executionData.vacuumSettings.retentionPeriod = $retentionPeriod + + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "Response Code: $statusCode" -Level Debug + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Table maintenance job successfully initiated for Lakehouse '$lakehouse.displayName'." -Level Info + return $response + } + 202 { + Write-Message -Message "Table maintenance job accepted and is now running in the background. Job execution is in progress." -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + + if ($waitForCompletion -eq $true) { + Write-Message -Message "Getting Long Running Operation status" -Level Debug + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location -retryAfter $retryAfter + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + return $operationStatus + } + else { + Write-Message -Message "The operation is running asynchronously." -Level Info + Write-Message -Message "Use the returned details to check the operation status." -Level Info + Write-Message -Message "To wait for the operation to complete, set the 'waitForCompletion' parameter to true." -Level Info + $operationDetails = [PSCustomObject]@{ + OperationId = $operationId + Location = $location + RetryAfter = $retryAfter + } + return $operationDetails + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to start table maintenance job. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Lakehouse/Update-FabricLakehouse.ps1 b/powershell/FabricACEToolkit/Public/Lakehouse/Update-FabricLakehouse.ps1 new file mode 100644 index 0000000..c4b9879 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Lakehouse/Update-FabricLakehouse.ps1 @@ -0,0 +1,108 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric Lakehouse. + +.DESCRIPTION +The `Update-FabricLakehouse` function updates the name and/or description of a specified Fabric Lakehouse by making a PATCH request to the API. + +.PARAMETER LakehouseId +The unique identifier of the Lakehouse to be updated. + +.PARAMETER LakehouseName +The new name for the Lakehouse. + +.PARAMETER LakehouseDescription +(Optional) The new description for the Lakehouse. + +.EXAMPLE +Update-FabricLakehouse -LakehouseId "Lakehouse123" -LakehouseName "NewLakehouseName" + +Updates the name of the Lakehouse with the ID "Lakehouse123" to "NewLakehouseName". + +.EXAMPLE +Update-FabricLakehouse -LakehouseId "Lakehouse123" -LakehouseName "NewName" -LakehouseDescription "Updated description" + +Updates both the name and description of the Lakehouse "Lakehouse123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricLakehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_]*$')] + [string]$LakehouseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/lakehouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $LakehouseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $LakehouseName + } + + if ($LakehouseDescription) { + $body.description = $LakehouseDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Lakehouse '$LakehouseName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Lakehouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/ML Experiment/Get-FabricMLExperiment.ps1 b/powershell/FabricACEToolkit/Public/ML Experiment/Get-FabricMLExperiment.ps1 new file mode 100644 index 0000000..52e57f8 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Experiment/Get-FabricMLExperiment.ps1 @@ -0,0 +1,156 @@ +<# +.SYNOPSIS + Retrieves ML Experiment details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves ML Experiment details from a specified workspace using either the provided MLExperimentId or MLExperimentName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the ML Experiment exists. This parameter is mandatory. + +.PARAMETER MLExperimentId + The unique identifier of the ML Experiment to retrieve. This parameter is optional. + +.PARAMETER MLExperimentName + The name of the ML Experiment to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentId "experiment-67890" + This example retrieves the ML Experiment details for the experiment with ID "experiment-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentName "My ML Experiment" + This example retrieves the ML Experiment details for the experiment named "My ML Experiment" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricMLExperiment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$MLExperimentName + ) + + try { + # Step 1: Handle ambiguous input + if ($MLExperimentId -and $MLExperimentName) { + Write-Message -Message "Both 'MLExperimentId' and 'MLExperimentName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $MLExperiments = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/mlExperiments" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $MLExperiments += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $MLExperiment = if ($MLExperimentId) { + $MLExperiments | Where-Object { $_.Id -eq $MLExperimentId } + } + elseif ($MLExperimentName) { + $MLExperiments | Where-Object { $_.DisplayName -eq $MLExperimentName } + } + else { + # Return all MLExperiments if no filter is provided + Write-Message -Message "No filter provided. Returning all MLExperiments." -Level Debug + $MLExperiments + } + + # Step 9: Handle results + if ($MLExperiment) { + Write-Message -Message "ML Experiment found matching the specified criteria." -Level Debug + return $MLExperiment + } + else { + Write-Message -Message "No ML Experiment found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve ML Experiment. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/ML Experiment/New-FabricMLExperiment.ps1 b/powershell/FabricACEToolkit/Public/ML Experiment/New-FabricMLExperiment.ps1 new file mode 100644 index 0000000..0a4d28b --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Experiment/New-FabricMLExperiment.ps1 @@ -0,0 +1,130 @@ +<# +.SYNOPSIS + Creates a new ML Experiment in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new ML Experiment + in the specified workspace. It supports optional parameters for ML Experiment description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the ML Experiment will be created. This parameter is mandatory. + +.PARAMETER MLExperimentName + The name of the ML Experiment to be created. This parameter is mandatory. + +.PARAMETER MLExperimentDescription + An optional description for the ML Experiment. + +.EXAMPLE + New-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentName "New ML Experiment" -MLExperimentDescription "Description of the new ML Experiment" + This example creates a new ML Experiment named "New ML Experiment" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function New-FabricMLExperiment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_]*$')] + [string]$MLExperimentName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mlExperiments" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $MLExperimentName + } + + if ($MLExperimentDescription) { + $body.description = $MLExperimentDescription + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "ML Experiment '$MLExperimentName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "ML Experiment '$MLExperimentName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create ML Experiment. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/ML Experiment/Remove-FabricMLExperiment.ps1 b/powershell/FabricACEToolkit/Public/ML Experiment/Remove-FabricMLExperiment.ps1 new file mode 100644 index 0000000..7c8cbb2 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Experiment/Remove-FabricMLExperiment.ps1 @@ -0,0 +1,72 @@ +<# +.SYNOPSIS + Removes an ML Experiment from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove an ML Experiment + from the specified workspace using the provided WorkspaceId and MLExperimentId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the MLExperiment will be removed. + +.PARAMETER MLExperimentId + The unique identifier of the MLExperiment to be removed. + +.EXAMPLE + Remove-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentId "experiment-67890" + This example removes the MLExperiment with ID "experiment-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Remove-FabricMLExperiment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mlExperiments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $MLExperimentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "ML Experiment '$MLExperimentId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete ML Experiment '$MLExperimentId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/ML Experiment/Update-FabricMLExperiment.ps1 b/powershell/FabricACEToolkit/Public/ML Experiment/Update-FabricMLExperiment.ps1 new file mode 100644 index 0000000..f9c0a9e --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Experiment/Update-FabricMLExperiment.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS + Updates an existing ML Experiment in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing ML Experiment + in the specified workspace. It supports optional parameters for ML Experiment description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the ML Experiment exists. This parameter is optional. + +.PARAMETER MLExperimentId + The unique identifier of the ML Experiment to be updated. This parameter is mandatory. + +.PARAMETER MLExperimentName + The new name of the ML Experiment. This parameter is mandatory. + +.PARAMETER MLExperimentDescription + An optional new description for the ML Experiment. + +.EXAMPLE + Update-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentId "experiment-67890" -MLExperimentName "Updated ML Experiment" -MLExperimentDescription "Updated description" + This example updates the ML Experiment with ID "experiment-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricMLExperiment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_]*$')] + [string]$MLExperimentName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mlExperiments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $MLExperimentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $MLExperimentName + } + + if ($MLExperimentDescription) { + $body.description = $MLExperimentDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "ML Experiment '$MLExperimentName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update ML Experiment. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/ML Model/Get-FabricMLModel.ps1 b/powershell/FabricACEToolkit/Public/ML Model/Get-FabricMLModel.ps1 new file mode 100644 index 0000000..7d15c5e --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Model/Get-FabricMLModel.ps1 @@ -0,0 +1,156 @@ +<# +.SYNOPSIS + Retrieves ML Model details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves ML Model details from a specified workspace using either the provided MLModelId or MLModelName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the ML Model exists. This parameter is mandatory. + +.PARAMETER MLModelId + The unique identifier of the ML Model to retrieve. This parameter is optional. + +.PARAMETER MLModelName + The name of the ML Model to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricMLModel -WorkspaceId "workspace-12345" -MLModelId "model-67890" + This example retrieves the ML Model details for the model with ID "model-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricMLModel -WorkspaceId "workspace-12345" -MLModelName "My ML Model" + This example retrieves the ML Model details for the model named "My ML Model" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricMLModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLModelId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$MLModelName + ) + + try { + # Step 1: Handle ambiguous input + if ($MLModelId -and $MLModelName) { + Write-Message -Message "Both 'MLModelId' and 'MLModelName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $MLModels = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/mlModels" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $MLModels += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $MLModel = if ($MLModelId) { + $MLModels | Where-Object { $_.Id -eq $MLModelId } + } + elseif ($MLModelName) { + $MLModels | Where-Object { $_.DisplayName -eq $MLModelName } + } + else { + # Return all MLModels if no filter is provided + Write-Message -Message "No filter provided. Returning all MLModels." -Level Debug + $MLModels + } + + # Step 9: Handle results + if ($MLModel) { + Write-Message -Message "ML Model found matching the specified criteria." -Level Debug + return $MLModel + } + else { + Write-Message -Message "No ML Model found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve ML Model. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/ML Model/New-FabricMLModel.ps1 b/powershell/FabricACEToolkit/Public/ML Model/New-FabricMLModel.ps1 new file mode 100644 index 0000000..cf4ffac --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Model/New-FabricMLModel.ps1 @@ -0,0 +1,130 @@ +<# +.SYNOPSIS + Creates a new ML Model in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new ML Model + in the specified workspace. It supports optional parameters for ML Model description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the ML Model will be created. This parameter is mandatory. + +.PARAMETER MLModelName + The name of the ML Model to be created. This parameter is mandatory. + +.PARAMETER MLModelDescription + An optional description for the ML Model. + +.EXAMPLE + New-FabricMLModel -WorkspaceId "workspace-12345" -MLModelName "New ML Model" -MLModelDescription "Description of the new ML Model" + This example creates a new ML Model named "New ML Model" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function New-FabricMLModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_]*$')] + [string]$MLModelName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLModelDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mlModels" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $MLModelName + } + + if ($MLModelDescription) { + $body.description = $MLModelDescription + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "ML Model '$MLModelName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "ML Model '$MLModelName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create ML Model. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/ML Model/Remove-FabricMLModel.ps1 b/powershell/FabricACEToolkit/Public/ML Model/Remove-FabricMLModel.ps1 new file mode 100644 index 0000000..f1491d7 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Model/Remove-FabricMLModel.ps1 @@ -0,0 +1,72 @@ +<# +.SYNOPSIS + Removes an ML Model from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove an ML Model + from the specified workspace using the provided WorkspaceId and MLModelId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the ML Model will be removed. + +.PARAMETER MLModelId + The unique identifier of the ML Model to be removed. + +.EXAMPLE + Remove-FabricMLModel -WorkspaceId "workspace-12345" -MLModelId "model-67890" + This example removes the ML Model with ID "model-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Remove-FabricMLModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MLModelId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mlModels/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $MLModelId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "ML Model '$MLModelId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete ML Model '$MLModelId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/ML Model/Update-FabricMLModel.ps1 b/powershell/FabricACEToolkit/Public/ML Model/Update-FabricMLModel.ps1 new file mode 100644 index 0000000..50e2d6a --- /dev/null +++ b/powershell/FabricACEToolkit/Public/ML Model/Update-FabricMLModel.ps1 @@ -0,0 +1,93 @@ +<# +.SYNOPSIS + Updates an existing ML Model in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing ML Model + in the specified workspace. It supports optional parameters for ML Model description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the ML Model exists. This parameter is optional. + +.PARAMETER MLModelId + The unique identifier of the ML Model to be updated. This parameter is mandatory. + +.PARAMETER MLModelDescription + New description for the ML Model. + +.EXAMPLE + Update-FabricMLModel -WorkspaceId "workspace-12345" -MLModelId "model-67890" -MLModelName "Updated ML Model" -MLModelDescription "Updated description" + This example updates the ML Model with ID "model-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricMLModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MLModelId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLModelDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mlModels/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $MLModelId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + description = $MLModelDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "ML Model '$MLModelId' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update ML Model. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 new file mode 100644 index 0000000..e5d9317 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 @@ -0,0 +1,157 @@ +<# +.SYNOPSIS +Retrieves an MirroredDatabase or a list of MirroredDatabases from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricMirroredDatabase` function sends a GET request to the Fabric API to retrieve MirroredDatabase details for a given workspace. It can filter the results by `MirroredDatabaseName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query MirroredDatabases. + +.PARAMETER MirroredDatabaseName +(Optional) The name of the specific MirroredDatabase to retrieve. + +.EXAMPLE +Get-FabricMirroredDatabase -WorkspaceId "12345" -MirroredDatabaseName "Development" + +Retrieves the "Development" MirroredDatabase from workspace "12345". + +.EXAMPLE +Get-FabricMirroredDatabase -WorkspaceId "12345" + +Retrieves all MirroredDatabases in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricMirroredDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$MirroredDatabaseName + ) + + try { + # Step 1: Handle ambiguous input + if ($MirroredDatabaseId -and $MirroredDatabaseName) { + Write-Message -Message "Both 'MirroredDatabaseId' and 'MirroredDatabaseName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + $continuationToken = $null + $MirroredDatabases = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases" -f $FabricConfig.BaseUrl, $WorkspaceId + + # Step 3: Loop to retrieve data with continuation token + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $MirroredDatabases += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + + # Step 8: Filter results based on provided parameters + $MirroredDatabase = if ($MirroredDatabaseId) { + $MirroredDatabases | Where-Object { $_.Id -eq $MirroredDatabaseId } + } + elseif ($MirroredDatabaseName) { + $MirroredDatabases | Where-Object { $_.DisplayName -eq $MirroredDatabaseName } + } + else { + # Return all MirroredDatabases if no filter is provided + Write-Message -Message "No filter provided. Returning all MirroredDatabases." -Level Debug + $MirroredDatabases + } + + # Step 9: Handle results + if ($MirroredDatabase) { + Write-Message -Message "MirroredDatabase found matching the specified criteria." -Level Debug + return $MirroredDatabase + } + else { + Write-Message -Message "No MirroredDatabase found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 new file mode 100644 index 0000000..2a7700c --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 @@ -0,0 +1,109 @@ + +<# +.SYNOPSIS +Retrieves the definition of a MirroredDatabase from a specific workspace in Microsoft Fabric. + +.DESCRIPTION +This function fetches the MirroredDatabase's content or metadata from a workspace. +Handles both synchronous and asynchronous operations, with detailed logging and error handling. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace from which the MirroredDatabase definition is to be retrieved. + +.PARAMETER MirroredDatabaseId +(Optional)The unique identifier of the MirroredDatabase whose definition needs to be retrieved. + +.EXAMPLE +Get-FabricMirroredDatabaseDefinition -WorkspaceId "12345" -MirroredDatabaseId "67890" + +Retrieves the definition of the MirroredDatabase with ID `67890` from the workspace with ID `12345`. + +.EXAMPLE +Get-FabricMirroredDatabaseDefinition -WorkspaceId "12345" + +Retrieves the definitions of all MirroredDatabases in the workspace with ID `12345`. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +#> +function Get-FabricMirroredDatabaseDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "MirroredDatabase '$MirroredDatabaseId' definition retrieved successfully!" -Level Debug + return $response.definition.parts + } + 202 { + + Write-Message -Message "Getting MirroredDatabase '$MirroredDatabaseId' definition request accepted. Retrieving in progress!" -Level Debug + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 new file mode 100644 index 0000000..200788c --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 @@ -0,0 +1,52 @@ +function Get-FabricMirroredDatabaseStatus { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/getMirroringStatus" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 9: Handle results + + Write-Message -Message "Returning status of MirroredDatabases." -Level Debug + return $response + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 new file mode 100644 index 0000000..f37c4cf --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 @@ -0,0 +1,97 @@ +function Get-FabricMirroredDatabaseTableStatus { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId + ) + + try { + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + $continuationToken = $null + $MirroredDatabaseTableStatus = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/getTablesMirroringStatus" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + + # Step 3: Loop to retrieve data with continuation token + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $MirroredDatabaseTableStatus += $response.data + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 9: Handle results + # Return all Mirrored Database Table Status + Write-Message -Message "No filter provided. Returning all MirroredDatabases." -Level Debug + $MirroredDatabaseTableStatus + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 new file mode 100644 index 0000000..70b4710 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 @@ -0,0 +1,186 @@ +<# +.SYNOPSIS +Creates a new MirroredDatabase in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new MirroredDatabase +in the specified workspace. It supports optional parameters for MirroredDatabase description +and path definitions for the MirroredDatabase content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the MirroredDatabase will be created. + +.PARAMETER MirroredDatabaseName +The name of the MirroredDatabase to be created. + +.PARAMETER MirroredDatabaseDescription +An optional description for the MirroredDatabase. + +.PARAMETER MirroredDatabasePathDefinition +An optional path to the MirroredDatabase definition file to upload. + +.PARAMETER MirroredDatabasePathPlatformDefinition +An optional path to the platform-specific definition (e.g., .platform file) to upload. + +.EXAMPLE + Add-FabricMirroredDatabase -WorkspaceId "workspace-12345" -MirroredDatabaseName "New MirroredDatabase" -MirroredDatabasePathDefinition "C:\MirroredDatabases\example.json" + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricMirroredDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$MirroredDatabaseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabasePathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabasePathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $MirroredDatabaseName + } + + if ($MirroredDatabaseDescription) { + $body.description = $MirroredDatabaseDescription + } + + if ($MirroredDatabasePathDefinition) { + $MirroredDatabaseEncodedContent = Convert-ToBase64 -filePath $MirroredDatabasePathDefinition + + if (-not [string]::IsNullOrEmpty($MirroredDatabaseEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "mirroredDatabase.json" + payload = $MirroredDatabaseEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in MirroredDatabase definition." -Level Error + return $null + } + } + + if ($MirroredDatabasePathPlatformDefinition) { + $MirroredDatabaseEncodedPlatformContent = Convert-ToBase64 -filePath $MirroredDatabasePathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($MirroredDatabaseEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "MirroredDatabase" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $MirroredDatabaseEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "MirroredDatabase '$MirroredDatabaseName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "MirroredDatabase '$MirroredDatabaseName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation Failed" -Level Debug + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create MirroredDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 new file mode 100644 index 0000000..701e513 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 @@ -0,0 +1,72 @@ +<# +.SYNOPSIS +Deletes an MirroredDatabase from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricMirroredDatabase` function sends a DELETE request to the Fabric API to remove a specified MirroredDatabase from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the MirroredDatabase to delete. + +.PARAMETER MirroredDatabaseId +(Mandatory) The ID of the MirroredDatabase to be deleted. + +.EXAMPLE +Remove-FabricMirroredDatabase -WorkspaceId "12345" -MirroredDatabaseId "67890" + +Deletes the MirroredDatabase with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch +#> + +function Remove-FabricMirroredDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "MirroredDatabase '$MirroredDatabaseId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete MirroredDatabase '$MirroredDatabaseId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 new file mode 100644 index 0000000..19f3bce --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 @@ -0,0 +1,51 @@ +function Start-FabricMirroredDatabaseMirroring{ + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/startMirroring" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 9: Handle results + Write-Message -Message "Database mirroring started successfully for MirroredDatabaseId: $MirroredDatabaseId" -Level Info + return + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to start MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 new file mode 100644 index 0000000..77d7404 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 @@ -0,0 +1,53 @@ + + +function Stop-FabricMirroredDatabaseMirroring{ + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/stopMirroring" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 9: Handle results + Write-Message -Message "Database mirroring stopped successfully for MirroredDatabaseId: $MirroredDatabaseId" -Level Info + return + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to stop MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 new file mode 100644 index 0000000..0969138 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 @@ -0,0 +1,107 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric MirroredDatabase. + +.DESCRIPTION +The `Update-FabricMirroredDatabase` function updates the name and/or description of a specified Fabric MirroredDatabase by making a PATCH request to the API. + +.PARAMETER MirroredDatabaseId +The unique identifier of the MirroredDatabase to be updated. + +.PARAMETER MirroredDatabaseName +The new name for the MirroredDatabase. + +.PARAMETER MirroredDatabaseDescription +(Optional) The new description for the MirroredDatabase. + +.EXAMPLE +Update-FabricMirroredDatabase -MirroredDatabaseId "MirroredDatabase123" -MirroredDatabaseName "NewMirroredDatabaseName" + +Updates the name of the MirroredDatabase with the ID "MirroredDatabase123" to "NewMirroredDatabaseName". + +.EXAMPLE +Update-FabricMirroredDatabase -MirroredDatabaseId "MirroredDatabase123" -MirroredDatabaseName "NewName" -MirroredDatabaseDescription "Updated description" + +Updates both the name and description of the MirroredDatabase "MirroredDatabase123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricMirroredDatabase { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$MirroredDatabaseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $MirroredDatabaseName + } + + if ($MirroredDatabaseDescription) { + $body.description = $MirroredDatabaseDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "MirroredDatabase '$MirroredDatabaseName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update MirroredDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 new file mode 100644 index 0000000..5fc7fb7 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 @@ -0,0 +1,168 @@ +<# +.SYNOPSIS +Updates the definition of a MirroredDatabase in a Microsoft Fabric workspace. + +.DESCRIPTION +This function allows updating the content or metadata of a MirroredDatabase in a Microsoft Fabric workspace. +The MirroredDatabase content can be provided as file paths, and metadata updates can optionally be enabled. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace where the MirroredDatabase resides. + +.PARAMETER MirroredDatabaseId +(Mandatory) The unique identifier of the MirroredDatabase to be updated. + +.PARAMETER MirroredDatabasePathDefinition +(Mandatory) The file path to the MirroredDatabase content definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER MirroredDatabasePathPlatformDefinition +(Optional) The file path to the MirroredDatabase's platform-specific definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER UpdateMetadata +(Optional)A boolean flag indicating whether to update the MirroredDatabase's metadata. +Default: `$false`. + +.EXAMPLE +Update-FabricMirroredDatabaseDefinition -WorkspaceId "12345" -MirroredDatabaseId "67890" -MirroredDatabasePathDefinition "C:\MirroredDatabases\MirroredDatabase.json" + +Updates the content of the MirroredDatabase with ID `67890` in the workspace `12345` using the specified MirroredDatabase file. + +.EXAMPLE +Update-FabricMirroredDatabaseDefinition -WorkspaceId "12345" -MirroredDatabaseId "67890" -MirroredDatabasePathDefinition "C:\MirroredDatabases\MirroredDatabase.json" -UpdateMetadata $true + +Updates both the content and metadata of the MirroredDatabase with ID `67890` in the workspace `12345`. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- The MirroredDatabase content is encoded as Base64 before being sent to the Fabric API. +- This function handles asynchronous operations and retrieves operation results if required. + +Author: Tiago Balabuch + +#> + +function Update-FabricMirroredDatabaseDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabasePathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabasePathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + + if($MirroredDatabasePathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + parts = @() + } + } + + if ($MirroredDatabasePathDefinition) { + $MirroredDatabaseEncodedContent = Convert-ToBase64 -filePath $MirroredDatabasePathDefinition + + if (-not [string]::IsNullOrEmpty($MirroredDatabaseEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "MirroredDatabase.json" + payload = $MirroredDatabaseEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in MirroredDatabase definition." -Level Error + return $null + } + } + + if ($MirroredDatabasePathPlatformDefinition) { + $MirroredDatabaseEncodedPlatformContent = Convert-ToBase64 -filePath $MirroredDatabasePathPlatformDefinition + if (-not [string]::IsNullOrEmpty($MirroredDatabaseEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $MirroredDatabaseEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for MirroredDatabase '$MirroredDatabaseId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for MirroredDatabase '$MirroredDatabaseId' accepted. Operation in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + $operationResult = Get-FabricLongRunningOperation -operationId $operationId + + # Handle operation result + if ($operationResult.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + + $result = Get-FabricLongRunningOperationResult -operationId $operationId + return $result.definition.parts + } + else { + Write-Message -Message "Operation Failed" -Level Debug + return $operationResult.definition.parts + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update MirroredDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 b/powershell/FabricACEToolkit/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 new file mode 100644 index 0000000..a5775d3 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 @@ -0,0 +1,157 @@ +<# +.SYNOPSIS +Retrieves an MirroredWarehouse or a list of MirroredWarehouses from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricMirroredWarehouse` function sends a GET request to the Fabric API to retrieve MirroredWarehouse details for a given workspace. It can filter the results by `MirroredWarehouseName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query MirroredWarehouses. + +.PARAMETER MirroredWarehouseName +(Optional) The name of the specific MirroredWarehouse to retrieve. + +.EXAMPLE +Get-FabricMirroredWarehouse -WorkspaceId "12345" -MirroredWarehouseName "Development" + +Retrieves the "Development" MirroredWarehouse from workspace "12345". + +.EXAMPLE +Get-FabricMirroredWarehouse -WorkspaceId "12345" + +Retrieves all MirroredWarehouses in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricMirroredWarehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredWarehouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$MirroredWarehouseName + ) + + try { + # Step 1: Handle ambiguous input + if ($MirroredWarehouseId -and $MirroredWarehouseName) { + Write-Message -Message "Both 'MirroredWarehouseId' and 'MirroredWarehouseName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + $continuationToken = $null + $MirroredWarehouses = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/MirroredWarehouses" -f $FabricConfig.BaseUrl, $WorkspaceId + + # Step 3: Loop to retrieve data with continuation token + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $MirroredWarehouses += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + + # Step 8: Filter results based on provided parameters + $MirroredWarehouse = if ($MirroredWarehouseId) { + $MirroredWarehouses | Where-Object { $_.Id -eq $MirroredWarehouseId } + } + elseif ($MirroredWarehouseName) { + $MirroredWarehouses | Where-Object { $_.DisplayName -eq $MirroredWarehouseName } + } + else { + # Return all MirroredWarehouses if no filter is provided + Write-Message -Message "No filter provided. Returning all MirroredWarehouses." -Level Debug + $MirroredWarehouses + } + + # Step 9: Handle results + if ($MirroredWarehouse) { + Write-Message -Message "MirroredWarehouse found matching the specified criteria." -Level Debug + return $MirroredWarehouse + } + else { + Write-Message -Message "No MirroredWarehouse found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredWarehouse. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Notebook/Get-FabricNotebook.ps1 b/powershell/FabricACEToolkit/Public/Notebook/Get-FabricNotebook.ps1 new file mode 100644 index 0000000..bd759f9 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Notebook/Get-FabricNotebook.ps1 @@ -0,0 +1,155 @@ +<# +.SYNOPSIS +Retrieves an Notebook or a list of Notebooks from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Get-FabricNotebook` function sends a GET request to the Fabric API to retrieve Notebook details for a given workspace. It can filter the results by `NotebookName`. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query Notebooks. + +.PARAMETER NotebookName +(Optional) The name of the specific Notebook to retrieve. + +.EXAMPLE +Get-FabricNotebook -WorkspaceId "12345" -NotebookName "Development" + +Retrieves the "Development" Notebook from workspace "12345". + +.EXAMPLE +Get-FabricNotebook -WorkspaceId "12345" + +Retrieves all Notebooks in workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricNotebook { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$NotebookName + ) + + try { + # Step 1: Handle ambiguous input + if ($NotebookId -and $NotebookName) { + Write-Message -Message "Both 'NotebookId' and 'NotebookName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $notebooks = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/notebooks" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $notebooks += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $notebook = if ($NotebookId) { + $notebooks | Where-Object { $_.Id -eq $NotebookId } + } + elseif ($NotebookName) { + $notebooks | Where-Object { $_.DisplayName -eq $NotebookName } + } + else { + # Return all notebooks if no filter is provided + Write-Message -Message "No filter provided. Returning all Notebooks." -Level Debug + $notebooks + } + + # Step 9: Handle results + if ($notebook) { + Write-Message -Message "Notebook found matching the specified criteria." -Level Debug + return $notebook + } + else { + Write-Message -Message "No notebook found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Notebook. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Notebook/Get-FabricNotebookDefinition.ps1 b/powershell/FabricACEToolkit/Public/Notebook/Get-FabricNotebookDefinition.ps1 new file mode 100644 index 0000000..009eb88 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Notebook/Get-FabricNotebookDefinition.ps1 @@ -0,0 +1,131 @@ + +<# +.SYNOPSIS +Retrieves the definition of a notebook from a specific workspace in Microsoft Fabric. + +.DESCRIPTION +This function fetches the notebook's content or metadata from a workspace. +It supports retrieving notebook definitions in the Jupyter Notebook (`ipynb`) format. +Handles both synchronous and asynchronous operations, with detailed logging and error handling. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace from which the notebook definition is to be retrieved. + +.PARAMETER NotebookId +(Optional)The unique identifier of the notebook whose definition needs to be retrieved. + +.PARAMETER NotebookFormat +Specifies the format of the notebook definition. Currently, only 'ipynb' is supported. +Default: 'ipynb'. + +.EXAMPLE +Get-FabricNotebookDefinition -WorkspaceId "12345" -NotebookId "67890" + +Retrieves the definition of the notebook with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + +.EXAMPLE +Get-FabricNotebookDefinition -WorkspaceId "12345" + +Retrieves the definitions of all notebooks in the workspace with ID `12345` in the `ipynb` format. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +#> +function Get-FabricNotebookDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('ipynb')] + [string]$NotebookFormat = 'ipynb' + ) + + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/notebooks/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $NotebookId + + if ($NotebookFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $NotebookFormat + } + + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "Notebook '$NotebookId' definition retrieved successfully!" -Level Debug + return $response + } + 202 { + + Write-Message -Message "Getting notebook '$NotebookId' definition request accepted. Retrieving in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + #[string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Notebook. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Notebook/New-FabricNotebook.ps1 b/powershell/FabricACEToolkit/Public/Notebook/New-FabricNotebook.ps1 new file mode 100644 index 0000000..eec94a4 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Notebook/New-FabricNotebook.ps1 @@ -0,0 +1,193 @@ +<# +.SYNOPSIS +Creates a new notebook in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new notebook +in the specified workspace. It supports optional parameters for notebook description +and path definitions for the notebook content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the notebook will be created. + +.PARAMETER NotebookName +The name of the notebook to be created. + +.PARAMETER NotebookDescription +An optional description for the notebook. + +.PARAMETER NotebookPathDefinition +An optional path to the notebook definition file (e.g., .ipynb file) to upload. + +.PARAMETER NotebookPathPlatformDefinition +An optional path to the platform-specific definition (e.g., .platform file) to upload. + +.EXAMPLE + Add-FabricNotebook -WorkspaceId "workspace-12345" -NotebookName "New Notebook" -NotebookPathDefinition "C:\notebooks\example.ipynb" + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricNotebook { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$NotebookName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/notebooks" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $NotebookName + } + + if ($NotebookDescription) { + $body.description = $NotebookDescription + } + + if ($NotebookPathDefinition) { + $notebookEncodedContent = Convert-ToBase64 -filePath $NotebookPathDefinition + + if (-not [string]::IsNullOrEmpty($notebookEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "ipynb" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "notebook-content.py" + payload = $notebookEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in notebook definition." -Level Error + return $null + } + } + + if ($NotebookPathPlatformDefinition) { + $notebookEncodedPlatformContent = Convert-ToBase64 -filePath $NotebookPathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($notebookEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "ipynb" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $notebookEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Notebook '$NotebookName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Notebook '$NotebookName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create notebook. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Notebook/New-FabricNotebookNEW.ps1 b/powershell/FabricACEToolkit/Public/Notebook/New-FabricNotebookNEW.ps1 new file mode 100644 index 0000000..c29b71f --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Notebook/New-FabricNotebookNEW.ps1 @@ -0,0 +1,158 @@ +<# +.SYNOPSIS +Creates a new notebook in a specified Microsoft Fabric workspace. + +.DESCRIPTION +This function sends a POST request to the Microsoft Fabric API to create a new notebook +in the specified workspace. It supports optional parameters for notebook description +and path definitions for the notebook content. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the notebook will be created. + +.PARAMETER NotebookName +The name of the notebook to be created. + +.PARAMETER NotebookDescription +An optional description for the notebook. + +.PARAMETER NotebookPathDefinition +An optional path to the notebook definition file (e.g., .ipynb file) to upload. + +.PARAMETER NotebookPathPlatformDefinition +An optional path to the platform-specific definition (e.g., .platform file) to upload. + +.EXAMPLE + Add-FabricNotebook -WorkspaceId "workspace-12345" -NotebookName "New Notebook" -NotebookPathDefinition "C:\notebooks\example.ipynb" + + .NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function New-FabricNotebookNEW { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$NotebookName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookPathDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/notebooks" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $NotebookName + } + + if ($NotebookDescription) { + $body.description = $NotebookDescription + } + + if ($NotebookPathDefinition) { + if (-not $body.definition) { + $body.definition = @{ + format = "ipynb" + parts = @() + } + } + $jsonObjectParts = Get-FileDefinitionParts -sourceDirectory $NotebookPathDefinition + # Add new part to the parts array + $body.definition.parts = $jsonObjectParts.parts + } + # Check if any path is .platform + foreach ($part in $jsonObjectParts.parts) { + if ($part.path -eq ".platform") { + $hasPlatformFile = $true + Write-Message -Message "Platform File: $hasPlatformFile" -Level Debug + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Notebook '$NotebookName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Notebook '$NotebookName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create notebook. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Notebook/Remove-FabricNotebook.ps1 b/powershell/FabricACEToolkit/Public/Notebook/Remove-FabricNotebook.ps1 new file mode 100644 index 0000000..ec22fad --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Notebook/Remove-FabricNotebook.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS +Deletes an Notebook from a specified workspace in Microsoft Fabric. + +.DESCRIPTION +The `Remove-FabricNotebook` function sends a DELETE request to the Fabric API to remove a specified Notebook from a given workspace. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace containing the Notebook to delete. + +.PARAMETER NotebookId +(Mandatory) The ID of the Notebook to be deleted. + +.EXAMPLE +Remove-FabricNotebook -WorkspaceId "12345" -NotebookId "67890" + +Deletes the Notebook with ID "67890" from workspace "12345". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Validates token expiration before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricNotebook { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$NotebookId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/notebooks/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $NotebookId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Notebook '$NotebookId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete notebook '$NotebookId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Notebook/Update-FabricNotebook.ps1 b/powershell/FabricACEToolkit/Public/Notebook/Update-FabricNotebook.ps1 new file mode 100644 index 0000000..c5cc820 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Notebook/Update-FabricNotebook.ps1 @@ -0,0 +1,107 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric Notebook. + +.DESCRIPTION +The `Update-FabricNotebook` function updates the name and/or description of a specified Fabric Notebook by making a PATCH request to the API. + +.PARAMETER NotebookId +The unique identifier of the Notebook to be updated. + +.PARAMETER NotebookName +The new name for the Notebook. + +.PARAMETER NotebookDescription +(Optional) The new description for the Notebook. + +.EXAMPLE +Update-FabricNotebook -NotebookId "Notebook123" -NotebookName "NewNotebookName" + +Updates the name of the Notebook with the ID "Notebook123" to "NewNotebookName". + +.EXAMPLE +Update-FabricNotebook -NotebookId "Notebook123" -NotebookName "NewName" -NotebookDescription "Updated description" + +Updates both the name and description of the Notebook "Notebook123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Update-FabricNotebook { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$NotebookId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$NotebookName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/notebooks/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $NotebookId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $NotebookName + } + + if ($NotebookDescription) { + $body.description = $NotebookDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Notebook '$NotebookName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update notebook. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Notebook/Update-FabricNotebookDefinition.ps1 b/powershell/FabricACEToolkit/Public/Notebook/Update-FabricNotebookDefinition.ps1 new file mode 100644 index 0000000..e627264 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Notebook/Update-FabricNotebookDefinition.ps1 @@ -0,0 +1,179 @@ +<# +.SYNOPSIS +Updates the definition of a notebook in a Microsoft Fabric workspace. + +.DESCRIPTION +This function allows updating the content or metadata of a notebook in a Microsoft Fabric workspace. +The notebook content can be provided as file paths, and metadata updates can optionally be enabled. + +.PARAMETER WorkspaceId +(Mandatory) The unique identifier of the workspace where the notebook resides. + +.PARAMETER NotebookId +(Mandatory) The unique identifier of the notebook to be updated. + +.PARAMETER NotebookPathDefinition +(Mandatory) The file path to the notebook content definition file. The content will be encoded as Base64 and sent in the request. + +.PARAMETER NotebookPathPlatformDefinition +(Optional) The file path to the notebook's platform-specific definition file. The content will be encoded as Base64 and sent in the request. + +.EXAMPLE +Update-FabricNotebookDefinition -WorkspaceId "12345" -NotebookId "67890" -NotebookPathDefinition "C:\Notebooks\Notebook.ipynb" + +Updates the content of the notebook with ID `67890` in the workspace `12345` using the specified notebook file. + +.EXAMPLE +Update-FabricNotebookDefinition -WorkspaceId "12345" -NotebookId "67890" -NotebookPathDefinition "C:\Notebooks\Notebook.ipynb" -NotebookPathPlatformDefinition "C:\Notebooks\.platform" + +Updates both the content and metadata of the notebook with ID `67890` in the workspace `12345`. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- The notebook content is encoded as Base64 before being sent to the Fabric API. +- This function handles asynchronous operations and retrieves operation results if required. + +Author: Tiago Balabuch + +#> + +function Update-FabricNotebookDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$NotebookId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$NotebookPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookPathPlatformDefinition + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/notebooks/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $NotebookId + + if ($NotebookPathPlatformDefinition) { + $apiEndpointUrl += "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + format = "ipynb" + parts = @() + } + } + + if ($NotebookPathDefinition) { + $notebookEncodedContent = Convert-ToBase64 -filePath $NotebookPathDefinition + + if (-not [string]::IsNullOrEmpty($notebookEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "notebook-content.py" + payload = $notebookEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in notebook definition." -Level Error + return $null + } + } + + if ($NotebookPathPlatformDefinition) { + $notebookEncodedPlatformContent = Convert-ToBase64 -filePath $NotebookPathPlatformDefinition + if (-not [string]::IsNullOrEmpty($notebookEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $notebookEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for notebook '$NotebookId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for notebook '$NotebookId' accepted. Operation in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update notebook. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 b/powershell/FabricACEToolkit/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 new file mode 100644 index 0000000..fc52257 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 @@ -0,0 +1,155 @@ +<# +.SYNOPSIS + Retrieves paginated report details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves paginated report details from a specified workspace using either the provided PaginatedReportId or PaginatedReportName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the paginated reports exist. This parameter is mandatory. + +.PARAMETER PaginatedReportId + The unique identifier of the paginated report to retrieve. This parameter is optional. + +.PARAMETER PaginatedReportName + The name of the paginated report to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricPaginatedReports -WorkspaceId "workspace-12345" -PaginatedReportId "report-67890" + This example retrieves the paginated report details for the report with ID "report-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricPaginatedReports -WorkspaceId "workspace-12345" -PaginatedReportName "My Paginated Report" + This example retrieves the paginated report details for the report named "My Paginated Report" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricPaginatedReport { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$PaginatedReportId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$PaginatedReportName + ) + + try { + # Step 1: Handle ambiguous input + if ($PaginatedReportId -and $PaginatedReportName) { + Write-Message -Message "Both 'PaginatedReportId' and 'PaginatedReportName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $PaginatedReports = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/paginatedReports" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $PaginatedReports += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $PaginatedReport = if ($PaginatedReportId) { + $PaginatedReports | Where-Object { $_.Id -eq $PaginatedReportId } + } + elseif ($PaginatedReportName) { + $PaginatedReports | Where-Object { $_.DisplayName -eq $PaginatedReportName } + } + else { + # Return all PaginatedReports if no filter is provided + Write-Message -Message "No filter provided. Returning all Paginated Reports." -Level Debug + $PaginatedReports + } + + # Step 9: Handle results + if ($PaginatedReport) { + Write-Message -Message "Paginated Report found matching the specified criteria." -Level Debug + return $PaginatedReport + } + else { + Write-Message -Message "No Paginated Report found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Paginated Report. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 b/powershell/FabricACEToolkit/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 new file mode 100644 index 0000000..00d0c59 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS + Updates an existing paginated report in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing paginated report + in the specified workspace. It supports optional parameters for paginated report description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the paginated report exists. This parameter is optional. + +.PARAMETER PaginatedReportId + The unique identifier of the paginated report to be updated. This parameter is mandatory. + +.PARAMETER PaginatedReportName + The new name of the paginated report. This parameter is mandatory. + +.PARAMETER PaginatedReportDescription + An optional new description for the paginated report. + +.EXAMPLE + Update-FabricPaginatedReport -WorkspaceId "workspace-12345" -PaginatedReportId "report-67890" -PaginatedReportName "Updated Paginated Report" -PaginatedReportDescription "Updated description" + This example updates the paginated report with ID "report-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricPaginatedReport { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$PaginatedReportId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$PaginatedReportName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$PaginatedReportDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/paginatedReports/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $PaginatedReportId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $PaginatedReportName + } + + if ($PaginatedReportDescription) { + $body.description = $PaginatedReportDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Paginated Report '$PaginatedReportName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Paginated Report. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Reflex/Get-FabricReflex.ps1 b/powershell/FabricACEToolkit/Public/Reflex/Get-FabricReflex.ps1 new file mode 100644 index 0000000..9e274d3 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Reflex/Get-FabricReflex.ps1 @@ -0,0 +1,156 @@ +<# +.SYNOPSIS + Retrieves Reflex details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves Reflex details from a specified workspace using either the provided ReflexId or ReflexName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Reflex exists. This parameter is mandatory. + +.PARAMETER ReflexId + The unique identifier of the Reflex to retrieve. This parameter is optional. + +.PARAMETER ReflexName + The name of the Reflex to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricReflex -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" + This example retrieves the Reflex details for the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricReflex -WorkspaceId "workspace-12345" -ReflexName "My Reflex" + This example retrieves the Reflex details for the Reflex named "My Reflex" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricReflex { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$ReflexName + ) + try { + + # Step 1: Handle ambiguous input + if ($ReflexId -and $ReflexName) { + Write-Message -Message "Both 'ReflexId' and 'ReflexName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $Reflexes = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/reflexes" -f $FabricConfig.BaseUrl, $WorkspaceId + # Step 3: Loop to retrieve data with continuation token + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $Reflexes += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $Reflex = if ($ReflexId) { + $Reflexes | Where-Object { $_.Id -eq $ReflexId } + } + elseif ($ReflexName) { + $Reflexes | Where-Object { $_.DisplayName -eq $ReflexName } + } + else { + # Return all Reflexes if no filter is provided + Write-Message -Message "No filter provided. Returning all Reflexes." -Level Debug + $Reflexes + } + + # Step 9: Handle results + if ($Reflex) { + Write-Message -Message "Reflex found in the Workspace '$WorkspaceId'." -Level Debug + return $Reflex + } + else { + Write-Message -Message "No Reflex found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Reflex. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Reflex/Get-FabricReflexDefinition.ps1 b/powershell/FabricACEToolkit/Public/Reflex/Get-FabricReflexDefinition.ps1 new file mode 100644 index 0000000..121677e --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Reflex/Get-FabricReflexDefinition.ps1 @@ -0,0 +1,124 @@ +<# +.SYNOPSIS + Retrieves the definition of an Reflex from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves the definition of an Reflex from a specified workspace using the provided ReflexId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Reflex exists. This parameter is mandatory. + +.PARAMETER ReflexId + The unique identifier of the Reflex to retrieve the definition for. This parameter is optional. + +.PARAMETER ReflexFormat + The format in which to retrieve the Reflex definition. This parameter is optional. + +.EXAMPLE + Get-FabricReflexDefinition -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" + This example retrieves the definition of the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricReflexDefinition -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" -ReflexFormat "json" + This example retrieves the definition of the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345" in JSON format. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricReflexDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexFormat + ) + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reflexes/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReflexId + + if ($ReflexFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $ReflexFormat + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "Reflex '$ReflexId' definition retrieved successfully!" -Level Debug + return $response.definition.parts + } + 202 { + + Write-Message -Message "Getting Reflex '$ReflexId' definition request accepted. Retrieving in progress!" -Level Debug + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId, -location $location + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Reflex. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Reflex/New-FabricReflex.ps1 b/powershell/FabricACEToolkit/Public/Reflex/New-FabricReflex.ps1 new file mode 100644 index 0000000..e71b650 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Reflex/New-FabricReflex.ps1 @@ -0,0 +1,193 @@ +<# +.SYNOPSIS + Creates a new Reflex in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new Reflex + in the specified workspace. It supports optional parameters for Reflex description and path definitions. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Reflex will be created. This parameter is mandatory. + +.PARAMETER ReflexName + The name of the Reflex to be created. This parameter is mandatory. + +.PARAMETER ReflexDescription + An optional description for the Reflex. + +.PARAMETER ReflexPathDefinition + An optional path to the Reflex definition file to upload. + +.PARAMETER ReflexPathPlatformDefinition + An optional path to the platform-specific definition file to upload. + +.EXAMPLE + New-FabricReflex -WorkspaceId "workspace-12345" -ReflexName "New Reflex" -ReflexDescription "Description of the new Reflex" + This example creates a new Reflex named "New Reflex" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function New-FabricReflex { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$ReflexName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexPathPlatformDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reflexes" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $ReflexName + } + + if ($ReflexDescription) { + $body.description = $ReflexDescription + } + if ($ReflexPathDefinition) { + $ReflexEncodedContent = Convert-ToBase64 -filePath $ReflexPathDefinition + + if (-not [string]::IsNullOrEmpty($ReflexEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "ReflexEntities.json" + payload = $ReflexEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in Reflex definition." -Level Error + return $null + } + } + + if ($ReflexPathPlatformDefinition) { + $ReflexEncodedPlatformContent = Convert-ToBase64 -filePath $ReflexPathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($ReflexEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $ReflexEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "Response Code: $statusCode" -Level Debug + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Reflex '$ReflexName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Reflex '$ReflexName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Reflex. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Reflex/Remove-FabricReflex.ps1 b/powershell/FabricACEToolkit/Public/Reflex/Remove-FabricReflex.ps1 new file mode 100644 index 0000000..884f4ab --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Reflex/Remove-FabricReflex.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS + Removes an Reflex from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove an Reflex + from the specified workspace using the provided WorkspaceId and ReflexId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the Reflex will be removed. + +.PARAMETER ReflexId + The unique identifier of the Reflex to be removed. + +.EXAMPLE + Remove-FabricReflex -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" + This example removes the Reflex with ID "Reflex-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Remove-FabricReflex { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReflexId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reflexes/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReflexId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle response + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Reflex '$ReflexId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete Reflex '$ReflexId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Reflex/Update-FabricReflex.ps1 b/powershell/FabricACEToolkit/Public/Reflex/Update-FabricReflex.ps1 new file mode 100644 index 0000000..a600d2f --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Reflex/Update-FabricReflex.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS + Updates an existing Reflex in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing Reflex + in the specified workspace. It supports optional parameters for Reflex description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Reflex exists. This parameter is optional. + +.PARAMETER ReflexId + The unique identifier of the Reflex to be updated. This parameter is mandatory. + +.PARAMETER ReflexName + The new name of the Reflex. This parameter is mandatory. + +.PARAMETER ReflexDescription + An optional new description for the Reflex. + +.EXAMPLE + Update-FabricReflex -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" -ReflexName "Updated Reflex" -ReflexDescription "Updated description" + This example updates the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricReflex { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReflexId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$ReflexName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexDescription + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reflexes/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReflexId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $ReflexName + } + + if ($ReflexDescription) { + $body.description = $ReflexDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Reflex '$ReflexName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Reflex. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Reflex/Update-FabricReflexDefinition.ps1 b/powershell/FabricACEToolkit/Public/Reflex/Update-FabricReflexDefinition.ps1 new file mode 100644 index 0000000..45582d9 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Reflex/Update-FabricReflexDefinition.ps1 @@ -0,0 +1,168 @@ +<# +.SYNOPSIS + Updates the definition of an existing Reflex in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update the definition of an existing Reflex + in the specified workspace. It supports optional parameters for Reflex definition and platform-specific definition. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Reflex exists. This parameter is mandatory. + +.PARAMETER ReflexId + The unique identifier of the Reflex to be updated. This parameter is mandatory. + +.PARAMETER ReflexPathDefinition + An optional path to the Reflex definition file to upload. + +.PARAMETER ReflexPathPlatformDefinition + An optional path to the platform-specific definition file to upload. + +.EXAMPLE + Update-FabricReflexDefinition -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" -ReflexPathDefinition "C:\Path\To\ReflexDefinition.json" + This example updates the definition of the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345" using the provided definition file. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricReflexDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReflexId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReflexPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexPathPlatformDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reflexes/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReflexId + + #if ($UpdateMetadata -eq $true) { + if($ReflexPathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + parts = @() + } + } + + if ($ReflexPathDefinition) { + $ReflexEncodedContent = Convert-ToBase64 -filePath $ReflexPathDefinition + + if (-not [string]::IsNullOrEmpty($ReflexEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "ReflexEntities.json" + payload = $ReflexEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in Reflex definition." -Level Error + return $null + } + } + + if ($ReflexPathPlatformDefinition) { + $ReflexEncodedPlatformContent = Convert-ToBase64 -filePath $ReflexPathPlatformDefinition + if (-not [string]::IsNullOrEmpty($ReflexEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $ReflexEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for Reflex '$ReflexId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for Reflex '$ReflexId' accepted. Operation in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Reflex. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Report/Get-FabricReport.ps1 b/powershell/FabricACEToolkit/Public/Report/Get-FabricReport.ps1 new file mode 100644 index 0000000..0f655be --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Report/Get-FabricReport.ps1 @@ -0,0 +1,156 @@ +<# +.SYNOPSIS + Retrieves Report details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves Report details from a specified workspace using either the provided ReportId or ReportName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Report exists. This parameter is mandatory. + +.PARAMETER ReportId + The unique identifier of the Report to retrieve. This parameter is optional. + +.PARAMETER ReportName + The name of the Report to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricReport -WorkspaceId "workspace-12345" -ReportId "Report-67890" + This example retrieves the Report details for the Report with ID "Report-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricReport -WorkspaceId "workspace-12345" -ReportName "My Report" + This example retrieves the Report details for the Report named "My Report" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricReport { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$ReportName + ) + try { + + # Step 1: Handle ambiguous input + if ($ReportId -and $ReportName) { + Write-Message -Message "Both 'ReportId' and 'ReportName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $Reports = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/reports" -f $FabricConfig.BaseUrl, $WorkspaceId + # Step 3: Loop to retrieve data with continuation token + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $Reports += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $Report = if ($ReportId) { + $Reports | Where-Object { $_.Id -eq $ReportId } + } + elseif ($ReportName) { + $Reports | Where-Object { $_.DisplayName -eq $ReportName } + } + else { + # Return all Reports if no filter is provided + Write-Message -Message "No filter provided. Returning all Reports." -Level Debug + $Reports + } + + # Step 9: Handle results + if ($Report) { + Write-Message -Message "Report found in the Workspace '$WorkspaceId'." -Level Debug + return $Report + } + else { + Write-Message -Message "No Report found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Report. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Report/Get-FabricReportDefinition.ps1 b/powershell/FabricACEToolkit/Public/Report/Get-FabricReportDefinition.ps1 new file mode 100644 index 0000000..ef06367 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Report/Get-FabricReportDefinition.ps1 @@ -0,0 +1,124 @@ +<# +.SYNOPSIS + Retrieves the definition of an Report from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves the definition of an Report from a specified workspace using the provided ReportId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Report exists. This parameter is mandatory. + +.PARAMETER ReportId + The unique identifier of the Report to retrieve the definition for. This parameter is optional. + +.PARAMETER ReportFormat + The format in which to retrieve the Report definition. This parameter is optional. + +.EXAMPLE + Get-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" + This example retrieves the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" -ReportFormat "json" + This example retrieves the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345" in JSON format. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricReportDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportFormat + ) + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reports/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReportId + + if ($ReportFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $ReportFormat + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "Report '$ReportId' definition retrieved successfully!" -Level Debug + return $response + } + 202 { + + Write-Message -Message "Getting Report '$ReportId' definition request accepted. Retrieving in progress!" -Level Debug + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Report. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Report/New-FabricReport.ps1 b/powershell/FabricACEToolkit/Public/Report/New-FabricReport.ps1 new file mode 100644 index 0000000..9e61167 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Report/New-FabricReport.ps1 @@ -0,0 +1,150 @@ +<# +.SYNOPSIS + Creates a new Report in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new Report + in the specified workspace. It supports optional parameters for Report description and path definitions. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Report will be created. This parameter is mandatory. + +.PARAMETER ReportName + The name of the Report to be created. This parameter is mandatory. + +.PARAMETER ReportDescription + An optional description for the Report. + +.PARAMETER ReportPathDefinition + A mandatory path to the folder that contains Report definition files to upload. + + +.EXAMPLE + New-FabricReport -WorkspaceId "workspace-12345" -ReportName "New Report" -ReportDescription "Description of the new Report" + This example creates a new Report named "New Report" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function New-FabricReport { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$ReportName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportDescription, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReportPathDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reports" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $ReportName + } + + if ($ReportDescription) { + $body.description = $ReportDescription + } + if ($ReportPathDefinition) { + if (-not $body.definition) { + $body.definition = @{ + parts = @() + } + } + $jsonObjectParts = Get-FileDefinitionParts -sourceDirectory $ReportPathDefinition + # Add new part to the parts array + $body.definition.parts = $jsonObjectParts.parts + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "Response Code: $statusCode" -Level Debug + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Report '$ReportName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Report '$ReportName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Report. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Report/Remove-FabricReport.ps1 b/powershell/FabricACEToolkit/Public/Report/Remove-FabricReport.ps1 new file mode 100644 index 0000000..3ab6977 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Report/Remove-FabricReport.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS + Removes an Report from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove an Report + from the specified workspace using the provided WorkspaceId and ReportId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the Report will be removed. + +.PARAMETER ReportId + The unique identifier of the Report to be removed. + +.EXAMPLE + Remove-FabricReport -WorkspaceId "workspace-12345" -ReportId "Report-67890" + This example removes the Report with ID "Report-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Remove-FabricReport { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReportId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reports/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReportId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle response + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Report '$ReportId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete Report '$ReportId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Report/Update-FabricReport.ps1 b/powershell/FabricACEToolkit/Public/Report/Update-FabricReport.ps1 new file mode 100644 index 0000000..08b852e --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Report/Update-FabricReport.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS + Updates an existing Report in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing Report + in the specified workspace. It supports optional parameters for Report description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Report exists. This parameter is optional. + +.PARAMETER ReportId + The unique identifier of the Report to be updated. This parameter is mandatory. + +.PARAMETER ReportName + The new name of the Report. This parameter is mandatory. + +.PARAMETER ReportDescription + An optional new description for the Report. + +.EXAMPLE + Update-FabricReport -WorkspaceId "workspace-12345" -ReportId "Report-67890" -ReportName "Updated Report" -ReportDescription "Updated description" + This example updates the Report with ID "Report-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricReport { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReportId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$ReportName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportDescription + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/reports/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReportId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $ReportName + } + + if ($ReportDescription) { + $body.description = $ReportDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Report '$ReportName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Report. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Report/Update-FabricReportDefinition.ps1 b/powershell/FabricACEToolkit/Public/Report/Update-FabricReportDefinition.ps1 new file mode 100644 index 0000000..1a7bb73 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Report/Update-FabricReportDefinition.ps1 @@ -0,0 +1,145 @@ +<# +.SYNOPSIS + Updates the definition of an existing Report in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update the definition of an existing Report + in the specified workspace. It supports optional parameters for Report definition and platform-specific definition. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Report exists. This parameter is mandatory. + +.PARAMETER ReportId + The unique identifier of the Report to be updated. This parameter is mandatory. + +.PARAMETER ReportPathDefinition + A mandatory path to the Report definition file to upload. + +.EXAMPLE + Update-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" -ReportPathDefinition "C:\Path\To\ReportDefinition.json" + This example updates the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345" using the provided definition file. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricReportDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReportId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReportPathDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/Reports/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReportId + + #if ($UpdateMetadata -eq $true) { + + + # Step 3: Construct the request body + $body = @{ + definition = @{ + parts = @() + } + } + + if ($ReportPathDefinition) { + if (-not $body.definition) { + $body.definition = @{ + parts = @() + } + } + $jsonObjectParts = Get-FileDefinitionParts -sourceDirectory $ReportPathDefinition + # Add new part to the parts array + $body.definition.parts = $jsonObjectParts.parts + } + # Check if any path is .platform + foreach ($part in $jsonObjectParts.parts) { + if ($part.path -eq ".platform") { + $hasPlatformFile = $true + Write-Message -Message "Platform File: $hasPlatformFile" -Level Debug + } + } + + if($hasPlatformFile -eq $true) { + $apiEndpointUrl += "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for Report '$ReportId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for Report '$ReportId' accepted. Operation in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Update definition operation for Report '$ReportId' succeeded!" -Level Info + return $operationStatus + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Report. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 b/powershell/FabricACEToolkit/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 new file mode 100644 index 0000000..6b760c9 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 @@ -0,0 +1,154 @@ +<# +.SYNOPSIS +Retrieves SQL Endpoints from a specified workspace in Fabric. + +.DESCRIPTION +The Get-FabricSQLEndpoint function retrieves SQL Endpoints from a specified workspace in Fabric. +It supports filtering by SQL Endpoint ID or SQL Endpoint Name. If both filters are provided, +an error message is returned. The function handles token validation, API requests with continuation +tokens, and processes the response to return the desired SQL Endpoint(s). + +.PARAMETER WorkspaceId +The ID of the workspace from which to retrieve SQL Endpoints. This parameter is mandatory. + +.PARAMETER SQLEndpointId +The ID of the SQL Endpoint to retrieve. This parameter is optional but cannot be used together with SQLEndpointName. + +.PARAMETER SQLEndpointName +The name of the SQL Endpoint to retrieve. This parameter is optional but cannot be used together with SQLEndpointId. + +.EXAMPLE +Get-FabricSQLEndpoint -WorkspaceId "workspace123" -SQLEndpointId "endpoint456" + +.EXAMPLE +Get-FabricSQLEndpoint -WorkspaceId "workspace123" -SQLEndpointName "MySQLEndpoint" + +.NOTES +- This function requires the FabricConfig object to be properly configured with BaseUrl and FabricHeaders. +- The function uses continuation tokens to handle paginated API responses. +- If no filter parameters are provided, all SQL Endpoints in the specified workspace are returned. + +#> +function Get-FabricSQLEndpoint { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SQLEndpointId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SQLEndpointName + ) + + try { + # Step 1: Handle ambiguous input + if ($SQLEndpointId -and $SQLEndpointName) { + Write-Message -Message "Both 'SQLEndpointId' and 'SQLEndpointName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $SQLEndpoints = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/SQLEndpoints" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $SQLEndpoints += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $SQLEndpoint = if ($SQLEndpointId) { + $SQLEndpoints | Where-Object { $_.Id -eq $SQLEndpointId } + } + elseif ($SQLEndpointName) { + $SQLEndpoints | Where-Object { $_.DisplayName -eq $SQLEndpointName } + } + else { + # Return all SQLEndpoints if no filter is provided + Write-Message -Message "No filter provided. Returning all Paginated Reports." -Level Debug + $SQLEndpoints + } + + # Step 9: Handle results + if ($SQLEndpoint) { + Write-Message -Message "Paginated Report found matching the specified criteria." -Level Debug + return $SQLEndpoint + } + else { + Write-Message -Message "No Paginated Report found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Paginated Report. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Semantic Model/Get-FabricSemanticModel.ps1 b/powershell/FabricACEToolkit/Public/Semantic Model/Get-FabricSemanticModel.ps1 new file mode 100644 index 0000000..f0611bd --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Semantic Model/Get-FabricSemanticModel.ps1 @@ -0,0 +1,156 @@ +<# +.SYNOPSIS + Retrieves SemanticModel details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves SemanticModel details from a specified workspace using either the provided SemanticModelId or SemanticModelName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SemanticModel exists. This parameter is mandatory. + +.PARAMETER SemanticModelId + The unique identifier of the SemanticModel to retrieve. This parameter is optional. + +.PARAMETER SemanticModelName + The name of the SemanticModel to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" + This example retrieves the SemanticModel details for the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelName "My SemanticModel" + This example retrieves the SemanticModel details for the SemanticModel named "My SemanticModel" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricSemanticModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SemanticModelName + ) + try { + + # Step 1: Handle ambiguous input + if ($SemanticModelId -and $SemanticModelName) { + Write-Message -Message "Both 'SemanticModelId' and 'SemanticModelName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $SemanticModels = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/semanticModels" -f $FabricConfig.BaseUrl, $WorkspaceId + # Step 3: Loop to retrieve data with continuation token + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $SemanticModels += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $SemanticModel = if ($SemanticModelId) { + $SemanticModels | Where-Object { $_.Id -eq $SemanticModelId } + } + elseif ($SemanticModelName) { + $SemanticModels | Where-Object { $_.DisplayName -eq $SemanticModelName } + } + else { + # Return all SemanticModels if no filter is provided + Write-Message -Message "No filter provided. Returning all SemanticModels." -Level Debug + $SemanticModels + } + + # Step 9: Handle results + if ($SemanticModel) { + Write-Message -Message "SemanticModel found in the Workspace '$WorkspaceId'." -Level Debug + return $SemanticModel + } + else { + Write-Message -Message "No SemanticModel found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SemanticModel. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 b/powershell/FabricACEToolkit/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 new file mode 100644 index 0000000..fa38d54 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 @@ -0,0 +1,125 @@ +<# +.SYNOPSIS + Retrieves the definition of an SemanticModel from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves the definition of an SemanticModel from a specified workspace using the provided SemanticModelId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SemanticModel exists. This parameter is mandatory. + +.PARAMETER SemanticModelId + The unique identifier of the SemanticModel to retrieve the definition for. This parameter is optional. + +.PARAMETER SemanticModelFormat + The format in which to retrieve the SemanticModel definition. This parameter is optional. + +.EXAMPLE + Get-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" + This example retrieves the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" -SemanticModelFormat "json" + This example retrieves the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345" in JSON format. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricSemanticModelDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('TMDL', 'TMSL')] + [string]$SemanticModelFormat = "TMDL" + ) + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/semanticModels/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $SemanticModelId + + if ($SemanticModelFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $SemanticModelFormat + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "SemanticModel '$SemanticModelId' definition retrieved successfully!" -Level Debug + return $response + } + 202 { + + Write-Message -Message "Getting SemanticModel '$SemanticModelId' definition request accepted. Retrieving in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SemanticModel. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Semantic Model/New-FabricSemanticModel.ps1 b/powershell/FabricACEToolkit/Public/Semantic Model/New-FabricSemanticModel.ps1 new file mode 100644 index 0000000..4ff05a0 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Semantic Model/New-FabricSemanticModel.ps1 @@ -0,0 +1,145 @@ +<# +.SYNOPSIS + Creates a new SemanticModel in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new SemanticModel + in the specified workspace. It supports optional parameters for SemanticModel description and path definitions. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SemanticModel will be created. This parameter is mandatory. + +.PARAMETER SemanticModelName + The name of the SemanticModel to be created. This parameter is mandatory. + +.PARAMETER SemanticModelDescription + An optional description for the SemanticModel. + +.PARAMETER SemanticModelPathDefinition + An optional path to the SemanticModel definition file to upload. + +.EXAMPLE + New-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelName "New SemanticModel" -SemanticModelDescription "Description of the new SemanticModel" + This example creates a new SemanticModel named "New SemanticModel" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function New-FabricSemanticModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SemanticModelName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelDescription, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelPathDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/semanticModels" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $SemanticModelName + definition = @{ + parts = @() + }} + + $jsonObjectParts = Get-FileDefinitionParts -sourceDirectory $SemanticModelPathDefinition + # Add new part to the parts array + $body.definition.parts = $jsonObjectParts.parts + + if ($SemanticModelDescription) { + $body.description = $SemanticModelDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "Response Code: $statusCode" -Level Debug + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "SemanticModel '$SemanticModelName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "SemanticModel '$SemanticModelName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create SemanticModel. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Semantic Model/Remove-FabricSemanticModel.ps1 b/powershell/FabricACEToolkit/Public/Semantic Model/Remove-FabricSemanticModel.ps1 new file mode 100644 index 0000000..4e12b22 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Semantic Model/Remove-FabricSemanticModel.ps1 @@ -0,0 +1,73 @@ +<# +.SYNOPSIS + Removes an SemanticModel from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove an SemanticModel + from the specified workspace using the provided WorkspaceId and SemanticModelId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the SemanticModel will be removed. + +.PARAMETER SemanticModelId + The unique identifier of the SemanticModel to be removed. + +.EXAMPLE + Remove-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" + This example removes the SemanticModel with ID "SemanticModel-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Remove-FabricSemanticModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/semanticModels/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SemanticModelId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle response + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "SemanticModel '$SemanticModelId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete SemanticModel '$SemanticModelId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Semantic Model/Update-FabricSemanticModel.ps1 b/powershell/FabricACEToolkit/Public/Semantic Model/Update-FabricSemanticModel.ps1 new file mode 100644 index 0000000..12974b5 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Semantic Model/Update-FabricSemanticModel.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS + Updates an existing SemanticModel in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing SemanticModel + in the specified workspace. It supports optional parameters for SemanticModel description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SemanticModel exists. This parameter is optional. + +.PARAMETER SemanticModelId + The unique identifier of the SemanticModel to be updated. This parameter is mandatory. + +.PARAMETER SemanticModelName + The new name of the SemanticModel. This parameter is mandatory. + +.PARAMETER SemanticModelDescription + An optional new description for the SemanticModel. + +.EXAMPLE + Update-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" -SemanticModelName "Updated SemanticModel" -SemanticModelDescription "Updated description" + This example updates the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricSemanticModel { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SemanticModelName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelDescription + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/semanticModels/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SemanticModelId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $SemanticModelName + } + + if ($SemanticModelDescription) { + $body.description = $SemanticModelDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "SemanticModel '$SemanticModelName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update SemanticModel. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 b/powershell/FabricACEToolkit/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 new file mode 100644 index 0000000..67e146e --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 @@ -0,0 +1,135 @@ +<# +.SYNOPSIS + Updates the definition of an existing SemanticModel in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update the definition of an existing SemanticModel + in the specified workspace. It supports optional parameters for SemanticModel definition and platform-specific definition. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SemanticModel exists. This parameter is mandatory. + +.PARAMETER SemanticModelId + The unique identifier of the SemanticModel to be updated. This parameter is mandatory. + +.PARAMETER SemanticModelPathDefinition + An optional path to the SemanticModel definition file to upload. + +.EXAMPLE + Update-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" -SemanticModelPathDefinition "C:\Path\To\SemanticModelDefinition.json" + This example updates the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345" using the provided definition file. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricSemanticModelDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelPathDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/SemanticModels/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $SemanticModelId + + # Step 3: Construct the request body + $body = @{ + definition = @{ + parts = @() + } + } + + $jsonObjectParts = Get-FileDefinitionParts -sourceDirectory $SemanticModelPathDefinition + # Add new part to the parts array + $body.definition.parts = $jsonObjectParts.parts + # Check if any path is .platform + foreach ($part in $jsonObjectParts.parts) { + if ($part.path -eq ".platform") { + $hasPlatformFile = $true + Write-Message -Message "Platform File: $hasPlatformFile" -Level Debug + } + } + + if ($hasPlatformFile -eq $true) { + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for SemanticModel '$SemanticModelId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for SemanticModel '$SemanticModelId' accepted. Operation in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Update definition operation for Semantic Model '$SemanticModelId' succeeded!" -Level Info + return $operationStatus + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update SemanticModel. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 b/powershell/FabricACEToolkit/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 new file mode 100644 index 0000000..09524fb --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 @@ -0,0 +1,156 @@ +<# +.SYNOPSIS + Retrieves Spark Job Definition details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves SparkJobDefinition details from a specified workspace using either the provided SparkJobDefinitionId or SparkJobDefinitionName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SparkJobDefinition exists. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionId + The unique identifier of the SparkJobDefinition to retrieve. This parameter is optional. + +.PARAMETER SparkJobDefinitionName + The name of the SparkJobDefinition to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" + This example retrieves the SparkJobDefinition details for the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionName "My SparkJobDefinition" + This example retrieves the SparkJobDefinition details for the SparkJobDefinition named "My SparkJobDefinition" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricSparkJobDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SparkJobDefinitionName + ) + try { + + # Step 1: Handle ambiguous input + if ($SparkJobDefinitionId -and $SparkJobDefinitionName) { + Write-Message -Message "Both 'SparkJobDefinitionId' and 'SparkJobDefinitionName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $SparkJobDefinitions = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/sparkJobDefinitions" -f $FabricConfig.BaseUrl, $WorkspaceId + # Step 3: Loop to retrieve data with continuation token + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $SparkJobDefinitions += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $SparkJobDefinition = if ($SparkJobDefinitionId) { + $SparkJobDefinitions | Where-Object { $_.Id -eq $SparkJobDefinitionId } + } + elseif ($SparkJobDefinitionName) { + $SparkJobDefinitions | Where-Object { $_.DisplayName -eq $SparkJobDefinitionName } + } + else { + # Return all SparkJobDefinitions if no filter is provided + Write-Message -Message "No filter provided. Returning all SparkJobDefinitions." -Level Debug + $SparkJobDefinitions + } + + # Step 9: Handle results + if ($SparkJobDefinition) { + Write-Message -Message "Spark Job Definition found in the Workspace '$WorkspaceId'." -Level Debug + return $SparkJobDefinition + } + else { + Write-Message -Message "No Spark Job Definition found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SparkJobDefinition. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 b/powershell/FabricACEToolkit/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 new file mode 100644 index 0000000..b1db8a9 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 @@ -0,0 +1,124 @@ +<# +.SYNOPSIS + Retrieves the definition of an SparkJobDefinition from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves the definition of an SparkJobDefinition from a specified workspace using the provided SparkJobDefinitionId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SparkJobDefinition exists. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionId + The unique identifier of the SparkJobDefinition to retrieve the definition for. This parameter is optional. + +.PARAMETER SparkJobDefinitionFormat + The format in which to retrieve the SparkJobDefinition definition. This parameter is optional. + +.EXAMPLE + Get-FabricSparkJobDefinitionDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" + This example retrieves the definition of the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricSparkJobDefinitionDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" -SparkJobDefinitionFormat "json" + This example retrieves the definition of the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345" in JSON format. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Get-FabricSparkJobDefinitionDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('SparkJobDefinitionV1')] + [string]$SparkJobDefinitionFormat = "SparkJobDefinitionV1" + ) + try { + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/sparkJobDefinitions/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkJobDefinitionId + + if ($SparkJobDefinitionFormat) { + $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $SparkJobDefinitionFormat + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code and handle the response + switch ($statusCode) { + 200 { + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionId' definition retrieved successfully!" -Level Debug + return $response.definition.parts + } + 202 { + + Write-Message -Message "Getting Spark Job Definition '$SparkJobDefinitionId' definition request accepted. Retrieving in progress!" -Level Debug + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId, -location $location + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult.definition.parts + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 9: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Spark Job Definition. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 b/powershell/FabricACEToolkit/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 new file mode 100644 index 0000000..99d992e --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 @@ -0,0 +1,194 @@ +<# +.SYNOPSIS + Creates a new SparkJobDefinition in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new SparkJobDefinition + in the specified workspace. It supports optional parameters for SparkJobDefinition description and path definitions. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SparkJobDefinition will be created. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionName + The name of the SparkJobDefinition to be created. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionDescription + An optional description for the SparkJobDefinition. + +.PARAMETER SparkJobDefinitionPathDefinition + An optional path to the SparkJobDefinition definition file to upload. + +.PARAMETER SparkJobDefinitionPathPlatformDefinition + An optional path to the platform-specific definition file to upload. + +.EXAMPLE + New-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionName "New SparkJobDefinition" -SparkJobDefinitionDescription "Description of the new SparkJobDefinition" + This example creates a new SparkJobDefinition named "New SparkJobDefinition" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function New-FabricSparkJobDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SparkJobDefinitionName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionPathPlatformDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/sparkJobDefinitions" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $SparkJobDefinitionName + } + + if ($SparkJobDefinitionDescription) { + $body.description = $SparkJobDefinitionDescription + } + if ($SparkJobDefinitionPathDefinition) { + $SparkJobDefinitionEncodedContent = Convert-ToBase64 -filePath $SparkJobDefinitionPathDefinition + + if (-not [string]::IsNullOrEmpty($SparkJobDefinitionEncodedContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "SparkJobDefinitionV1" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = "SparkJobDefinitionProperties.json" + payload = $SparkJobDefinitionEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in SparkJobDefinition definition." -Level Error + return $null + } + } + + if ($SparkJobDefinitionPathPlatformDefinition) { + $SparkJobDefinitionEncodedPlatformContent = Convert-ToBase64 -filePath $SparkJobDefinitionPathPlatformDefinition + + if (-not [string]::IsNullOrEmpty($SparkJobDefinitionEncodedPlatformContent)) { + # Initialize definition if it doesn't exist + if (-not $body.definition) { + $body.definition = @{ + format = "SparkJobDefinitionV1" + parts = @() + } + } + + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $SparkJobDefinitionEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "Response Code: $statusCode" -Level Debug + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Spark Job Definition. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 b/powershell/FabricACEToolkit/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 new file mode 100644 index 0000000..68f8e18 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 @@ -0,0 +1,72 @@ +<# +.SYNOPSIS + Removes an SparkJobDefinition from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove an SparkJobDefinition + from the specified workspace using the provided WorkspaceId and SparkJobDefinitionId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the SparkJobDefinition will be removed. + +.PARAMETER SparkJobDefinitionId + The unique identifier of the SparkJobDefinition to be removed. + +.EXAMPLE + Remove-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" + This example removes the SparkJobDefinition with ID "SparkJobDefinition-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Remove-FabricSparkJobDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/sparkJobDefinitions/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkJobDefinitionId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle response + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete SparkJobDefinition '$SparkJobDefinitionId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 b/powershell/FabricACEToolkit/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 new file mode 100644 index 0000000..43bb3da --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 @@ -0,0 +1,118 @@ +<# +.SYNOPSIS + Starts a Fabric Spark Job Definition on demand. + +.DESCRIPTION + This function initiates a Spark Job Definition on demand within a specified workspace. + It constructs the appropriate API endpoint URL and makes a POST request to start the job. + The function can optionally wait for the job to complete based on the 'waitForCompletion' parameter. + +.PARAMETER WorkspaceId + The ID of the workspace where the Spark Job Definition is located. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionId + The ID of the Spark Job Definition to be started. This parameter is mandatory. + +.PARAMETER JobType + The type of job to be started. The default value is 'sparkjob'. This parameter is optional. + +.PARAMETER waitForCompletion + A boolean flag indicating whether to wait for the job to complete. The default value is $false. This parameter is optional. + +.EXAMPLE + Start-FabricSparkJobDefinitionOnDemand -WorkspaceId "workspace123" -SparkJobDefinitionId "jobdef456" -waitForCompletion $true + +.NOTES + Ensure that the necessary authentication tokens are valid before running this function. + The function logs detailed messages for debugging and informational purposes. +#> +function Start-FabricSparkJobDefinitionOnDemand { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('sparkjob')] + [string]$JobType = "sparkjob", + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$waitForCompletion = $false + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/SparkJobDefinitions/{2}/jobs/instances?jobType={3}" -f $FabricConfig.BaseUrl, $WorkspaceId , $SparkJobDefinitionId, $JobType + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + Write-Message -Message "Response Code: $statusCode" -Level Debug + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Spark Job Definition on demand successfully initiated for SparkJobDefinition '$SparkJobDefinition.displayName'." -Level Info + return $response + } + 202 { + Write-Message -Message "Spark Job Definition on demand accepted and is now running in the background. Job execution is in progress." -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + + if ($waitForCompletion -eq $true) { + Write-Message -Message "Getting Long Running Operation status" -Level Debug + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location -retryAfter $retryAfter + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + return $operationStatus + } + else { + Write-Message -Message "The operation is running asynchronously." -Level Info + Write-Message -Message "Use the returned details to check the operation status." -Level Info + Write-Message -Message "To wait for the operation to complete, set the 'waitForCompletion' parameter to true." -Level Info + $operationDetails = [PSCustomObject]@{ + OperationId = $operationId + Location = $location + RetryAfter = $retryAfter + } + return $operationDetails + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to start Spark Job Definition on demand. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 b/powershell/FabricACEToolkit/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 new file mode 100644 index 0000000..9b2c641 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 @@ -0,0 +1,104 @@ +<# +.SYNOPSIS + Updates an existing SparkJobDefinition in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing SparkJobDefinition + in the specified workspace. It supports optional parameters for SparkJobDefinition description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SparkJobDefinition exists. This parameter is optional. + +.PARAMETER SparkJobDefinitionId + The unique identifier of the SparkJobDefinition to be updated. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionName + The new name of the SparkJobDefinition. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionDescription + An optional new description for the SparkJobDefinition. + +.EXAMPLE + Update-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" -SparkJobDefinitionName "Updated SparkJobDefinition" -SparkJobDefinitionDescription "Updated description" + This example updates the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Update-FabricSparkJobDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SparkJobDefinitionName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionDescription + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/sparkJobDefinitions/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkJobDefinitionId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $SparkJobDefinitionName + } + + if ($SparkJobDefinitionDescription) { + $body.description = $SparkJobDefinitionDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update SparkJobDefinition. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 b/powershell/FabricACEToolkit/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 new file mode 100644 index 0000000..cca084d --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 @@ -0,0 +1,168 @@ +<# +.SYNOPSIS + Updates the definition of an existing SparkJobDefinition in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update the definition of an existing SparkJobDefinition + in the specified workspace. It supports optional parameters for SparkJobDefinition definition and platform-specific definition. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the SparkJobDefinition exists. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionId + The unique identifier of the SparkJobDefinition to be updated. This parameter is mandatory. + +.PARAMETER SparkJobDefinitionPathDefinition + An optional path to the SparkJobDefinition definition file to upload. + +.PARAMETER SparkJobDefinitionPathPlatformDefinition + An optional path to the platform-specific definition file to upload. + +.EXAMPLE + Update-FabricSparkJobDefinitionDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" -SparkJobDefinitionPathDefinition "C:\Path\To\SparkJobDefinitionDefinition.json" + This example updates the definition of the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345" using the provided definition file. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Update-FabricSparkJobDefinitionDefinition { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionPathDefinition, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionPathPlatformDefinition + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/SparkJobDefinitions/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkJobDefinitionId + + #if ($UpdateMetadata -eq $true) { + if($SparkJobDefinitionPathPlatformDefinition){ + $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + definition = @{ + format = "SparkJobDefinitionV1" + parts = @() + } + } + + if ($SparkJobDefinitionPathDefinition) { + $SparkJobDefinitionEncodedContent = Convert-ToBase64 -filePath $SparkJobDefinitionPathDefinition + + if (-not [string]::IsNullOrEmpty($SparkJobDefinitionEncodedContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = "SparkJobDefinitionV1.json" + payload = $SparkJobDefinitionEncodedContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in SparkJobDefinition definition." -Level Error + return $null + } + } + + if ($SparkJobDefinitionPathPlatformDefinition) { + $SparkJobDefinitionEncodedPlatformContent = Convert-ToBase64 -filePath $SparkJobDefinitionPathPlatformDefinition + if (-not [string]::IsNullOrEmpty($SparkJobDefinitionEncodedPlatformContent)) { + # Add new part to the parts array + $body.definition.parts += @{ + path = ".platform" + payload = $SparkJobDefinitionEncodedPlatformContent + payloadType = "InlineBase64" + } + } + else { + Write-Message -Message "Invalid or empty content in platform definition." -Level Error + return $null + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Update definition for Spark Job Definition '$SparkJobDefinitionId' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Update definition for Spark Job Definition '$SparkJobDefinitionId' accepted. Operation in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Spark Job Definition. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark/Get-FabricSparkCustomPool.ps1 b/powershell/FabricACEToolkit/Public/Spark/Get-FabricSparkCustomPool.ps1 new file mode 100644 index 0000000..6bf0441 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark/Get-FabricSparkCustomPool.ps1 @@ -0,0 +1,161 @@ +<# +.SYNOPSIS + Retrieves Spark custom pools from a specified workspace. + +.DESCRIPTION + This function retrieves all Spark custom pools from a specified workspace using the provided WorkspaceId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + The function supports filtering by SparkCustomPoolId or SparkCustomPoolName, but not both simultaneously. + +.PARAMETER WorkspaceId + The ID of the workspace from which to retrieve Spark custom pools. This parameter is mandatory. + +.PARAMETER SparkCustomPoolId + The ID of the specific Spark custom pool to retrieve. This parameter is optional. + +.PARAMETER SparkCustomPoolName + The name of the specific Spark custom pool to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricSparkCustomPool -WorkspaceId "12345" + This example retrieves all Spark custom pools from the workspace with ID "12345". + +.EXAMPLE + Get-FabricSparkCustomPool -WorkspaceId "12345" -SparkCustomPoolId "pool1" + This example retrieves the Spark custom pool with ID "pool1" from the workspace with ID "12345". + +.EXAMPLE + Get-FabricSparkCustomPool -WorkspaceId "12345" -SparkCustomPoolName "MyPool" + This example retrieves the Spark custom pool with name "MyPool" from the workspace with ID "12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + - Handles continuation tokens to retrieve all Spark custom pools if there are multiple pages of results. + + Author: Tiago Balabuch +#> +function Get-FabricSparkCustomPool { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkCustomPoolId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SparkCustomPoolName + ) + + try { + # Step 1: Handle ambiguous input + if ($SparkCustomPoolId -and $SparkCustomPoolName) { + Write-Message -Message "Both 'SparkCustomPoolId' and 'SparkCustomPoolName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $SparkCustomPools = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/spark/pools" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $SparkCustomPools += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $SparkCustomPool = if ($SparkCustomPoolId) { + $SparkCustomPools | Where-Object { $_.id -eq $SparkCustomPoolId } + } + elseif ($SparkCustomPoolName) { + $SparkCustomPools | Where-Object { $_.name -eq $SparkCustomPoolName } + } + else { + # Return all SparkCustomPools if no filter is provided + Write-Message -Message "No filter provided. Returning all SparkCustomPools." -Level Debug + $SparkCustomPools + } + + # Step 9: Handle results + if ($SparkCustomPool) { + Write-Message -Message "SparkCustomPool found matching the specified criteria." -Level Debug + return $SparkCustomPool + } + else { + Write-Message -Message "No SparkCustomPool found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SparkCustomPool. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Spark/Get-FabricSparkSettings.ps1 b/powershell/FabricACEToolkit/Public/Spark/Get-FabricSparkSettings.ps1 new file mode 100644 index 0000000..11c5c51 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark/Get-FabricSparkSettings.ps1 @@ -0,0 +1,119 @@ +<# +.SYNOPSIS + Retrieves Spark settings from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves Spark settings from a specified workspace using the provided WorkspaceId. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which to retrieve Spark settings. This parameter is mandatory. + +.EXAMPLE + Get-FabricSparkSettings -WorkspaceId "workspace-12345" + This example retrieves the Spark settings for the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Get-FabricSparkSettings { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId + ) + + try { + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $SparkSettings = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/spark/settings" -f $FabricConfig.BaseUrl, $WorkspaceId + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $SparkSettings += $response + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 9: Handle results + if ($SparkSettings) { + Write-Message -Message " Returning all Spark Settings." -Level Debug + # Return all Spark Settings + return $SparkSettings + } + else { + Write-Message -Message "No SparkSettings found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SparkSettings. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Spark/New-FabricSparkCustomPool.ps1 b/powershell/FabricACEToolkit/Public/Spark/New-FabricSparkCustomPool.ps1 new file mode 100644 index 0000000..848677c --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark/New-FabricSparkCustomPool.ps1 @@ -0,0 +1,190 @@ +<# +.SYNOPSIS + Creates a new Spark custom pool in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new Spark custom pool + in the specified workspace. It supports various parameters for Spark custom pool configuration. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Spark custom pool will be created. This parameter is mandatory. + +.PARAMETER SparkCustomPoolName + The name of the Spark custom pool to be created. This parameter is mandatory. + +.PARAMETER NodeFamily + The family of nodes to be used in the Spark custom pool. This parameter is mandatory and must be 'MemoryOptimized'. + +.PARAMETER NodeSize + The size of the nodes to be used in the Spark custom pool. This parameter is mandatory and must be one of 'Large', 'Medium', 'Small', 'XLarge', 'XXLarge'. + +.PARAMETER AutoScaleEnabled + Specifies whether auto-scaling is enabled for the Spark custom pool. This parameter is mandatory. + +.PARAMETER AutoScaleMinNodeCount + The minimum number of nodes for auto-scaling in the Spark custom pool. This parameter is mandatory. + +.PARAMETER AutoScaleMaxNodeCount + The maximum number of nodes for auto-scaling in the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationEnabled + Specifies whether dynamic executor allocation is enabled for the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationMinExecutors + The minimum number of executors for dynamic executor allocation in the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationMaxExecutors + The maximum number of executors for dynamic executor allocation in the Spark custom pool. This parameter is mandatory. + +.EXAMPLE + New-FabricSparkCustomPool -WorkspaceId "workspace-12345" -SparkCustomPoolName "New Spark Pool" -NodeFamily "MemoryOptimized" -NodeSize "Large" -AutoScaleEnabled $true -AutoScaleMinNodeCount 1 -AutoScaleMaxNodeCount 10 -DynamicExecutorAllocationEnabled $true -DynamicExecutorAllocationMinExecutors 1 -DynamicExecutorAllocationMaxExecutors 10 + This example creates a new Spark custom pool named "New Spark Pool" in the workspace with ID "workspace-12345" with the specified configuration. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> + +function New-FabricSparkCustomPool { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$SparkCustomPoolName, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('MemoryOptimized')] + [string]$NodeFamily, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Large', 'Medium', 'Small', 'XLarge', 'XXLarge')] + [string]$NodeSize, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [bool]$AutoScaleEnabled, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$AutoScaleMinNodeCount, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$AutoScaleMaxNodeCount, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [bool]$DynamicExecutorAllocationEnabled, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$DynamicExecutorAllocationMinExecutors, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$DynamicExecutorAllocationMaxExecutors + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/spark/pools" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + name = $SparkCustomPoolName + nodeFamily = $NodeFamily + nodeSize = $NodeSize + autoScale = @{ + enabled = $AutoScaleEnabled + minNodeCount = $AutoScaleMinNodeCount + maxNodeCount = $AutoScaleMaxNodeCount + } + dynamicExecutorAllocation = @{ + enabled = $DynamicExecutorAllocationEnabled + minExecutors = $DynamicExecutorAllocationMinExecutors + maxExecutors = $DynamicExecutorAllocationMaxExecutors + } + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "SparkCustomPool '$SparkCustomPoolName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "SparkCustomPool '$SparkCustomPoolName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId, -location $location + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create SparkCustomPool. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark/Remove-FabricSparkCustomPool.ps1 b/powershell/FabricACEToolkit/Public/Spark/Remove-FabricSparkCustomPool.ps1 new file mode 100644 index 0000000..2b748e6 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark/Remove-FabricSparkCustomPool.ps1 @@ -0,0 +1,72 @@ +<# +.SYNOPSIS + Removes a Spark custom pool from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove a Spark custom pool + from the specified workspace using the provided WorkspaceId and SparkCustomPoolId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the Spark custom pool will be removed. + +.PARAMETER SparkCustomPoolId + The unique identifier of the Spark custom pool to be removed. + +.EXAMPLE + Remove-FabricSparkCustomPool -WorkspaceId "workspace-12345" -SparkCustomPoolId "pool-67890" + This example removes the Spark custom pool with ID "pool-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Remove-FabricSparkCustomPool { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SparkCustomPoolId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/spark/pools/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkCustomPoolId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Spark Custom Pool '$SparkCustomPoolId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete SparkCustomPool '$SparkCustomPoolId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark/Update-FabricSparkCustomPool.ps1 b/powershell/FabricACEToolkit/Public/Spark/Update-FabricSparkCustomPool.ps1 new file mode 100644 index 0000000..9e4bcfd --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark/Update-FabricSparkCustomPool.ps1 @@ -0,0 +1,164 @@ +<# +.SYNOPSIS + Updates an existing Spark custom pool in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing Spark custom pool + in the specified workspace. It supports various parameters for Spark custom pool configuration. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Spark custom pool exists. This parameter is mandatory. + +.PARAMETER SparkCustomPoolId + The unique identifier of the Spark custom pool to be updated. This parameter is mandatory. + +.PARAMETER InstancePoolName + The new name of the Spark custom pool. This parameter is mandatory. + +.PARAMETER NodeFamily + The family of nodes to be used in the Spark custom pool. This parameter is mandatory and must be 'MemoryOptimized'. + +.PARAMETER NodeSize + The size of the nodes to be used in the Spark custom pool. This parameter is mandatory and must be one of 'Large', 'Medium', 'Small', 'XLarge', 'XXLarge'. + +.PARAMETER AutoScaleEnabled + Specifies whether auto-scaling is enabled for the Spark custom pool. This parameter is mandatory. + +.PARAMETER AutoScaleMinNodeCount + The minimum number of nodes for auto-scaling in the Spark custom pool. This parameter is mandatory. + +.PARAMETER AutoScaleMaxNodeCount + The maximum number of nodes for auto-scaling in the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationEnabled + Specifies whether dynamic executor allocation is enabled for the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationMinExecutors + The minimum number of executors for dynamic executor allocation in the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationMaxExecutors + The maximum number of executors for dynamic executor allocation in the Spark custom pool. This parameter is mandatory. + +.EXAMPLE + Update-FabricSparkCustomPool -WorkspaceId "workspace-12345" -SparkCustomPoolId "pool-67890" -InstancePoolName "Updated Spark Pool" -NodeFamily "MemoryOptimized" -NodeSize "Large" -AutoScaleEnabled $true -AutoScaleMinNodeCount 1 -AutoScaleMaxNodeCount 10 -DynamicExecutorAllocationEnabled $true -DynamicExecutorAllocationMinExecutors 1 -DynamicExecutorAllocationMaxExecutors 10 + This example updates the Spark custom pool with ID "pool-67890" in the workspace with ID "workspace-12345" with a new name and configuration. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricSparkCustomPool { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SparkCustomPoolId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$InstancePoolName, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('MemoryOptimized')] + [string]$NodeFamily, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Large', 'Medium', 'Small', 'XLarge', 'XXLarge')] + [string]$NodeSize, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [bool]$AutoScaleEnabled, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$AutoScaleMinNodeCount, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$AutoScaleMaxNodeCount, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [bool]$DynamicExecutorAllocationEnabled, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$DynamicExecutorAllocationMinExecutors, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [int]$DynamicExecutorAllocationMaxExecutors + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/spark/pools/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkCustomPoolId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + name = $InstancePoolName + nodeFamily = $NodeFamily + nodeSize = $NodeSize + autoScale = @{ + enabled = $AutoScaleEnabled + minNodeCount = $AutoScaleMinNodeCount + maxNodeCount = $AutoScaleMaxNodeCount + } + dynamicExecutorAllocation = @{ + enabled = $DynamicExecutorAllocationEnabled + minExecutors = $DynamicExecutorAllocationMinExecutors + maxExecutors = $DynamicExecutorAllocationMaxExecutors + } + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Spark Custom Pool '$SparkCustomPoolName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update SparkCustomPool. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Spark/Update-FabricSparkSettings.ps1 b/powershell/FabricACEToolkit/Public/Spark/Update-FabricSparkSettings.ps1 new file mode 100644 index 0000000..9320af8 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Spark/Update-FabricSparkSettings.ps1 @@ -0,0 +1,189 @@ +<# +.SYNOPSIS + Updates an existing Spark custom pool in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing Spark custom pool + in the specified workspace. It supports various parameters for Spark custom pool configuration. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the Spark custom pool exists. This parameter is mandatory. + +.PARAMETER SparkSettingsId + The unique identifier of the Spark custom pool to be updated. This parameter is mandatory. + +.PARAMETER InstancePoolName + The new name of the Spark custom pool. This parameter is mandatory. + +.PARAMETER NodeFamily + The family of nodes to be used in the Spark custom pool. This parameter is mandatory and must be 'MemoryOptimized'. + +.PARAMETER NodeSize + The size of the nodes to be used in the Spark custom pool. This parameter is mandatory and must be one of 'Large', 'Medium', 'Small', 'XLarge', 'XXLarge'. + +.PARAMETER AutoScaleEnabled + Specifies whether auto-scaling is enabled for the Spark custom pool. This parameter is mandatory. + +.PARAMETER AutoScaleMinNodeCount + The minimum number of nodes for auto-scaling in the Spark custom pool. This parameter is mandatory. + +.PARAMETER AutoScaleMaxNodeCount + The maximum number of nodes for auto-scaling in the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationEnabled + Specifies whether dynamic executor allocation is enabled for the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationMinExecutors + The minimum number of executors for dynamic executor allocation in the Spark custom pool. This parameter is mandatory. + +.PARAMETER DynamicExecutorAllocationMaxExecutors + The maximum number of executors for dynamic executor allocation in the Spark custom pool. This parameter is mandatory. + +.EXAMPLE + Update-FabricSparkSettings -WorkspaceId "workspace-12345" -SparkSettingsId "pool-67890" -InstancePoolName "Updated Spark Pool" -NodeFamily "MemoryOptimized" -NodeSize "Large" -AutoScaleEnabled $true -AutoScaleMinNodeCount 1 -AutoScaleMaxNodeCount 10 -DynamicExecutorAllocationEnabled $true -DynamicExecutorAllocationMinExecutors 1 -DynamicExecutorAllocationMaxExecutors 10 + This example updates the Spark custom pool with ID "pool-67890" in the workspace with ID "workspace-12345" with a new name and configuration. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricSparkSettings { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$automaticLogEnabled, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$notebookInteractiveRunEnabled, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$customizeComputeEnabled, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$defaultPoolName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Workspace', 'Capacity')] + [string]$defaultPoolType, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$starterPoolMaxNode, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [int]$starterPoolMaxExecutors, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentRuntimeVersion + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/spark/settings" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkSettingsId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + # Construct the request body with optional properties + + $body = @{} + + if ($PSBoundParameters.ContainsKey('automaticLogEnabled')) { + $body.automaticLog = @{ + enabled = $automaticLogEnabled + } + } + + if ($PSBoundParameters.ContainsKey('notebookInteractiveRunEnabled')) { + $body.highConcurrency = @{ + notebookInteractiveRunEnabled = $notebookInteractiveRunEnabled + } + } + + if ($PSBoundParameters.ContainsKey('customizeComputeEnabled') ) { + $body.pool = @{ + customizeComputeEnabled = $customizeComputeEnabled + } + } + if ($PSBoundParameters.ContainsKey('defaultPoolName') -or $PSBoundParameters.ContainsKey('defaultPoolType')) { + if ($PSBoundParameters.ContainsKey('defaultPoolName') -and $PSBoundParameters.ContainsKey('defaultPoolType')) { + $body.pool = @{ + defaultPool = @{ + name = $defaultPoolName + type = $defaultPoolType + } + } + } else { + Write-Message -Message "Both 'defaultPoolName' and 'defaultPoolType' must be provided together." -Level Error + throw + } + } + + if ($PSBoundParameters.ContainsKey('EnvironmentName') -or $PSBoundParameters.ContainsKey('EnvironmentRuntimeVersion')) { + $body.environment = @{ + name = $EnvironmentName + } + } + if ($PSBoundParameters.ContainsKey('EnvironmentRuntimeVersion')) { + $body.environment = @{ + runtimeVersion = $EnvironmentRuntimeVersion + } + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Spark Custom Pool '$SparkSettingsName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update SparkSettings. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Tenant/Get-FabricTenantSetting.ps1 b/powershell/FabricACEToolkit/Public/Tenant/Get-FabricTenantSetting.ps1 new file mode 100644 index 0000000..5af6ca3 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Tenant/Get-FabricTenantSetting.ps1 @@ -0,0 +1,94 @@ +<# +.SYNOPSIS +Retrieves tenant settings from the Fabric environment. + +.DESCRIPTION +The `Get-FabricTenantSetting` function retrieves tenant settings for a Fabric environment by making a GET request to the appropriate API endpoint. Optionally, it filters the results by the `SettingTitle` parameter. + +.PARAMETER SettingTitle +(Optional) The title of a specific tenant setting to filter the results. + +.EXAMPLE +Get-FabricTenantSetting + +Returns all tenant settings. + +.EXAMPLE +Get-FabricTenantSetting -SettingTitle "SomeSetting" + +Returns the tenant setting with the title "SomeSetting". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Is-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricTenantSetting { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SettingTitle + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/admin/tenantsettings" -f $FabricConfig.BaseUrl + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 5: Handle empty response + if (-not $response) { + Write-Message -Message "No data returned from the API." -Level Warning + return $null + } + # Step 6: Filter results based on provided parameters + $settings = if ($SettingTitle) { + $response.tenantSettings | Where-Object { $_.title -eq $SettingTitle } + } + else { + # Return all workspaces if no filter is provided + Write-Message -Message "No filter provided. Returning all tenant settings." -Level Debug + $response.tenantSettings + } + + # Step 7: Handle results + if ($settings) { + return $settings + } + else { + Write-Message -Message "No tenant settings found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 8: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve tenant settings. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Tenant/Get-FabricTenantSettingOverridesCapacity.ps1 b/powershell/FabricACEToolkit/Public/Tenant/Get-FabricTenantSettingOverridesCapacity.ps1 new file mode 100644 index 0000000..10a64f3 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Tenant/Get-FabricTenantSettingOverridesCapacity.ps1 @@ -0,0 +1,109 @@ +<# +.SYNOPSIS +Retrieves capacities tenant settings overrides from the Fabric tenant. + +.DESCRIPTION +The `Get-FabricTenantSetting` function retrieves capacities tenant settings overrides for a Fabric tenant by making a GET request to the appropriate API endpoint. + +.EXAMPLE +Get-FabricTenantSettingOverridesCapacity + +Returns all capacities tenant settings overrides. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Is-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Get-FabricTenantSettingOverridesCapacity { + [CmdletBinding()] + param () + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $capacitiesOverrides = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/admin/capacities/delegatedTenantSettingOverrides" -f $FabricConfig.BaseUrl + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $capacitiesOverrides += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + # Step 7: Handle results + if ($capacitiesOverrides) { + Write-Message -Message "Capacities overrides found." -Level Debug + return $capacitiesOverrides + } + else { + Write-Message -Message "No capacity capacities tenant settings overrides overrides found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 8: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve capacities tenant settings overrides. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Utils/Convert-FromBase64.ps1 b/powershell/FabricACEToolkit/Public/Utils/Convert-FromBase64.ps1 new file mode 100644 index 0000000..5aa99e1 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Utils/Convert-FromBase64.ps1 @@ -0,0 +1,55 @@ +<# +.SYNOPSIS + Decodes a Base64-encoded string into its original text representation. + +.DESCRIPTION + The Convert-FromBase64 function takes a Base64-encoded string as input, decodes it into a byte array, + and converts it back into a UTF-8 encoded string. It is useful for reversing Base64 encoding applied + to text or other data. + +.PARAMETER Base64String + The Base64-encoded string that you want to decode. + +.EXAMPLE + Convert-FromBase64 -Base64String "SGVsbG8sIFdvcmxkIQ==" + + Output: + Hello, World! + +.EXAMPLE + $encodedString = "U29tZSBlbmNvZGVkIHRleHQ=" + Convert-FromBase64 -Base64String $encodedString + + Output: + Some encoded text + +.NOTES + - This function assumes the Base64 input is a valid UTF-8 encoded string. + - Any decoding errors will throw a descriptive error message. + +.AUTHOR +Tiago Balabuch +#> +function Convert-FromBase64 { + param ( + [Parameter(Mandatory = $true)] + [string]$Base64String + ) + + try { + # Step 1: Convert the Base64 string to a byte array + $bytes = [Convert]::FromBase64String($Base64String) + + # Step 2: Convert the byte array back to a UTF-8 string + $decodedString = [System.Text.Encoding]::UTF8.GetString($bytes) + + # Step 3: Return the decoded string + return $decodedString + } + catch { + # Step 4: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "An error occurred while decoding from Base64: $errorDetails" -Level Error + throw "An error occurred while decoding from Base64: $_" + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Utils/Convert-ToBase64.ps1 b/powershell/FabricACEToolkit/Public/Utils/Convert-ToBase64.ps1 new file mode 100644 index 0000000..8b15256 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Utils/Convert-ToBase64.ps1 @@ -0,0 +1,60 @@ +<# +.SYNOPSIS + Encodes the content of a file into a Base64-encoded string. + +.DESCRIPTION + The Convert-ToBase64 function takes a file path as input, reads the file's content as a byte array, + and converts it into a Base64-encoded string. This is useful for embedding binary data (e.g., images, + documents) in text-based formats such as JSON or XML. + +.PARAMETER filePath + The full path to the file whose contents you want to encode into Base64. + +.EXAMPLE + Convert-ToBase64 -filePath "C:\Path\To\File.txt" + + Output: + VGhpcyBpcyBhbiBlbmNvZGVkIGZpbGUu + +.EXAMPLE + $encodedContent = Convert-ToBase64 -filePath "C:\Path\To\Image.jpg" + $encodedContent | Set-Content -Path "C:\Path\To\EncodedImage.txt" + + This saves the Base64-encoded content of the image to a text file. + +.NOTES + - Ensure the file exists at the specified path before running this function. + - Large files may cause memory constraints due to full loading into memory. + +.AUTHOR +Tiago Balabuch +#> +function Convert-ToBase64 { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$filePath + ) + try { + + # Step 1: Reading all the bytes from the file + #$bytes = [System.Text.Encoding]::UTF8.GetBytes($InputString) + Write-Message -Message "Reading all the bytes from the file specified: $filePath" -Level Debug + $fileBytes = [System.IO.File]::ReadAllBytes($filePath) + + # Step 2: Convert the byte array to Base64 string + Write-Message -Message "Convert the byte array to Base64 string" -Level Debug + $base64String = [Convert]::ToBase64String($fileBytes) + + # Step 3: Return the encoded string + Write-Message -Message "Return the encoded string for the file: $filePath" -Level Debug + return $base64String + } + catch { + # Step 4: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "An error occurred while encoding to Base64: $errorDetails" -Level Error + throw "An error occurred while encoding to Base64: $_" + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Utils/Get-FabricLongRunningOperation.ps1 b/powershell/FabricACEToolkit/Public/Utils/Get-FabricLongRunningOperation.ps1 new file mode 100644 index 0000000..4fa2cc0 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Utils/Get-FabricLongRunningOperation.ps1 @@ -0,0 +1,88 @@ +<# +.SYNOPSIS +Monitors the status of a long-running operation in Microsoft Fabric. + +.DESCRIPTION +The Get-FabricLongRunningOperation function queries the Microsoft Fabric API to check the status of a +long-running operation. It periodically polls the operation until it reaches a terminal state (Succeeded or Failed). + +.PARAMETER operationId +The unique identifier of the long-running operation to be monitored. + +.PARAMETER retryAfter +The interval (in seconds) to wait between polling the operation status. The default is 5 seconds. + +.EXAMPLE +Get-FabricLongRunningOperation -operationId "12345-abcd-67890-efgh" -retryAfter 10 + +This command polls the status of the operation with the given operationId every 10 seconds until it completes. + +.NOTES +- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. + +.AUTHOR +Tiago Balabuch + +#> +function Get-FabricLongRunningOperation { + param ( + [Parameter(Mandatory = $false)] + [string]$operationId, + + [Parameter(Mandatory = $false)] + [string]$location, + + [Parameter(Mandatory = $false)] + [int]$retryAfter = 5 + ) + + # Step 1: Construct the API URL + if ($location) { + # Use the Location header to define the operationUrl + $apiEndpointUrl = $location + } + else { + $apiEndpointUrl = "https://api.fabric.microsoft.com/v1/operations/{0}" -f $operationId + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + try { + do { + + # Step 2: Wait before the next request + if ($retryAfter) { + Start-Sleep -Seconds $retryAfter + } + else { + Start-Sleep -Seconds 5 # Default retry interval if no Retry-After header + } + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -ResponseHeadersVariable responseHeader ` + -StatusCodeVariable statusCode + + # Step 3: Parse the response + $jsonOperation = $response | ConvertTo-Json + $operation = $jsonOperation | ConvertFrom-Json + + # Log status for debugging + Write-Message -Message "Operation Status: $($operation.status)" -Level Debug + + + } while ($operation.status -notin @("Succeeded", "Completed", "Failed")) + + # Step 5: Return the operation result + return $operation + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "An error occurred while checking the operation: $errorDetails" -Level Error + throw + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Utils/Get-FabricLongRunningOperationResult.ps1 b/powershell/FabricACEToolkit/Public/Utils/Get-FabricLongRunningOperationResult.ps1 new file mode 100644 index 0000000..00000c6 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Utils/Get-FabricLongRunningOperationResult.ps1 @@ -0,0 +1,67 @@ +<# +.SYNOPSIS +Retrieves the result of a completed long-running operation from the Microsoft Fabric API. + +.DESCRIPTION +The Get-FabricLongRunningOperationResult function queries the Microsoft Fabric API to fetch the result +of a specific long-running operation. This is typically used after confirming the operation has completed successfully. + +.PARAMETER operationId +The unique identifier of the completed long-running operation whose result you want to retrieve. + +.EXAMPLE +Get-FabricLongRunningOperationResult -operationId "12345-abcd-67890-efgh" + +This command fetches the result of the operation with the specified operationId. + +.NOTES +- Ensure the Fabric API headers (e.g., authorization tokens) are defined in $FabricConfig.FabricHeaders. +- This function does not handle polling. Ensure the operation is in a terminal state before calling this function. + +.AUTHOR +Tiago Balabuch + +#> +function Get-FabricLongRunningOperationResult { + param ( + [Parameter(Mandatory = $true)] + [string]$operationId + ) + + # Step 1: Construct the API URL + $apiEndpointUrl = "https://api.fabric.microsoft.com/v1/operations/{0}/result" -f $operationId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + try { + # Step 2: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + + # Step 3: Return the result + Write-Message -Message "Result response code: $statusCode" -Level Debug + Write-Message -Message "Result return: $response" -Level Debug + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Debug + Write-Message -Message "Error: $($response.message)" -Level Debug + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Debug + Write-Message "Error Code: $($response.errorCode)" -Level Debug + } + + return $response + } + catch { + # Step 3: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "An error occurred while returning the operation result: $errorDetails" -Level Error + throw + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Utils/Set-FabricApiHeaders.ps1 b/powershell/FabricACEToolkit/Public/Utils/Set-FabricApiHeaders.ps1 new file mode 100644 index 0000000..e1c7a43 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Utils/Set-FabricApiHeaders.ps1 @@ -0,0 +1,116 @@ +<# +.SYNOPSIS +Sets the Fabric API headers with a valid token for the specified Azure tenant. + +.DESCRIPTION +The `Set-FabricApiHeaders` function logs into the specified Azure tenant, retrieves an access token for the Fabric API, and sets the necessary headers for subsequent API requests. +It also updates the token expiration time and global tenant ID. + +.PARAMETER TenantId +The Azure tenant ID for which the access token is requested. + +.PARAMETER AppId +The Azure app ID for which the service principal access token is requested. + +.PARAMETER AppSecret +The Azure App secret for which the service principal access token is requested. + +.EXAMPLE +Set-FabricApiHeaders -TenantId "your-tenant-id" + +Logs in to Azure with the specified tenant ID, retrieves an access token for the current user, and configures the Fabric headers. + +.EXAMPLE +$tenantId = "999999999-99999-99999-9999-999999999999" +$appId = "888888888-88888-88888-8888-888888888888" +$appSecret = "your-app-secret" +$secureAppSecret = $appSecret | ConvertTo-SecureString -AsPlainText -Force + +Set-FabricApiHeader -TenantId $tenantId -AppId $appId -AppSecret $secureAppSecret +Logs in to Azure with the specified tenant ID, retrieves an access token for the service principal, and configures the Fabric headers. + +.NOTES +- Ensure the `Connect-AzAccount` and `Get-AzAccessToken` commands are available (Azure PowerShell module required). +- Relies on a global `$FabricConfig` object for storing headers and token metadata. + +.AUTHOR +Tiago Balabuch +#> + +function Set-FabricApiHeaders { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$TenantId, + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$AppId, + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [System.Security.SecureString]$AppSecret + ) + + try { + # Step 1: Connect to the Azure account + Write-Message -Message "Logging in to Azure tenant: $TenantId" -Level Info + + # Step 2: Performing validation checks on the parameters passed to a function or script. + # Checks if 'AppId' is provided without 'AppSecret' and vice versa. + if ($PSBoundParameters.ContainsKey('AppId') -and -not $PSBoundParameters.ContainsKey('AppSecret')) { + Write-Message -Message "AppSecret is required when using AppId: $AppId" -Level Error + throw "AppSecret is required when using AppId." + } + if ($PSBoundParameters.ContainsKey('AppSecret') -and -not $PSBoundParameters.ContainsKey('AppId')) { + Write-Message -Message "AppId is required when using AppSecret." -Level Error + throw "AppId is required when using AppId." + } + # Step 3: Connect to the Azure account + # Using AppId and AppSecret + if ($PSBoundParameters.ContainsKey('AppId') -and $PSBoundParameters.ContainsKey('AppSecret')) { + + Write-Message -Message "Logging in using the AppId: $AppId" -Level Debug + Write-Message -Message "Logging in using the AppId: $AppId" -Level Info + $psCredential = [pscredential]::new($AppId, $AppSecret) + Connect-AzAccount -ServicePrincipal -Credential $psCredential -Tenant $tenantId + + } + # Using the current user + else { + + Write-Message -Message "Logging in using the current user" -Level Debug + Write-Message -Message "Logging in using the current user" -Level Info + Connect-AzAccount -Tenant $TenantId -ErrorAction Stop | Out-Null + } + + ## Step 4: Retrieve the access token for the Fabric API + Write-Message -Message "Retrieve the access token for the Fabric API: $TenantId" -Level Debug + $fabricToken = Get-AzAccessToken -AsSecureString -ResourceUrl $FabricConfig.ResourceUrl -ErrorAction Stop -WarningAction SilentlyContinue + + ## Step 5: Extract the plain token from the secure string + Write-Message -Message "Extract the plain token from the secure string" -Level Debug + $plainToken = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto( + [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($fabricToken.Token) + ) + + ## Step 6: Set the headers in the global configuration + Write-Message -Message "Set the headers in the global configuration" -Level Debug + $FabricConfig.FabricHeaders = @{ + 'Content-Type' = 'application/json' + 'Authorization' = "Bearer $plainToken" + } + + ## Step 7: Update token metadata in the global configuration + Write-Message -Message "Update token metadata in the global configuration" -Level Debug + $FabricConfig.TokenExpiresOn = $fabricToken.ExpiresOn + $FabricConfig.TenantIdGlobal = $TenantId + + Write-Message -Message "Fabric token successfully configured." -Level Info + } + catch { + # Step 8: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to set Fabric token: $errorDetails" -Level Error + throw "Unable to configure Fabric token. Ensure tenant and API configurations are correct." + } +} diff --git a/powershell/FabricACEToolkit/Public/Warehouse/Get-FabricWarehouse.ps1 b/powershell/FabricACEToolkit/Public/Warehouse/Get-FabricWarehouse.ps1 new file mode 100644 index 0000000..9945564 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Warehouse/Get-FabricWarehouse.ps1 @@ -0,0 +1,155 @@ +<# +.SYNOPSIS + Retrieves warehouse details from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function retrieves warehouse details from a specified workspace using either the provided WarehouseId or WarehouseName. + It handles token validation, constructs the API URL, makes the API request, and processes the response. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the warehouse exists. This parameter is mandatory. + +.PARAMETER WarehouseId + The unique identifier of the warehouse to retrieve. This parameter is optional. + +.PARAMETER WarehouseName + The name of the warehouse to retrieve. This parameter is optional. + +.EXAMPLE + Get-FabricWarehouse -WorkspaceId "workspace-12345" -WarehouseId "warehouse-67890" + This example retrieves the warehouse details for the warehouse with ID "warehouse-67890" in the workspace with ID "workspace-12345". + +.EXAMPLE + Get-FabricWarehouse -WorkspaceId "workspace-12345" -WarehouseName "My Warehouse" + This example retrieves the warehouse details for the warehouse named "My Warehouse" in the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Get-FabricWarehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WarehouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$WarehouseName + ) + + try { + # Step 1: Handle ambiguous input + if ($WarehouseId -and $WarehouseName) { + Write-Message -Message "Both 'WarehouseId' and 'WarehouseName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + # Step 3: Initialize variables + $continuationToken = $null + $Warehouses = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/warehouses" -f $FabricConfig.BaseUrl, $WorkspaceId + + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $Warehouses += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $Warehouse = if ($WarehouseId) { + $Warehouses | Where-Object { $_.Id -eq $WarehouseId } + } + elseif ($WarehouseName) { + $Warehouses | Where-Object { $_.DisplayName -eq $WarehouseName } + } + else { + # Return all Warehouses if no filter is provided + Write-Message -Message "No filter provided. Returning all Warehouses." -Level Debug + $Warehouses + } + + # Step 9: Handle results + if ($Warehouse) { + Write-Message -Message "Warehouse found matching the specified criteria." -Level Debug + return $Warehouse + } + else { + Write-Message -Message "No Warehouse found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Warehouse. Error: $errorDetails" -Level Error + } + +} diff --git a/powershell/FabricACEToolkit/Public/Warehouse/New-FabricWarehouse.ps1 b/powershell/FabricACEToolkit/Public/Warehouse/New-FabricWarehouse.ps1 new file mode 100644 index 0000000..db77148 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Warehouse/New-FabricWarehouse.ps1 @@ -0,0 +1,129 @@ +<# +.SYNOPSIS + Creates a new warehouse in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a POST request to the Microsoft Fabric API to create a new warehouse + in the specified workspace. It supports optional parameters for warehouse description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the warehouse will be created. This parameter is mandatory. + +.PARAMETER WarehouseName + The name of the warehouse to be created. This parameter is mandatory. + +.PARAMETER WarehouseDescription + An optional description for the warehouse. + +.EXAMPLE + New-FabricWarehouse -WorkspaceId "workspace-12345" -WarehouseName "New Warehouse" -WarehouseDescription "Description of the new warehouse" + This example creates a new warehouse named "New Warehouse" in the workspace with ID "workspace-12345" with the provided description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function New-FabricWarehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$WarehouseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WarehouseDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/warehouses" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $WarehouseName + } + + if ($WarehouseDescription) { + $body.description = $WarehouseDescription + } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Warehouse '$WarehouseName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Warehouse '$WarehouseName' creation accepted. Provisioning in progress!" -Level Info + + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId -location $location + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Warehouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Warehouse/Remove-FabricWarehouse.ps1 b/powershell/FabricACEToolkit/Public/Warehouse/Remove-FabricWarehouse.ps1 new file mode 100644 index 0000000..d4fb4c7 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Warehouse/Remove-FabricWarehouse.ps1 @@ -0,0 +1,71 @@ +<# +.SYNOPSIS + Removes a warehouse from a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a DELETE request to the Microsoft Fabric API to remove a warehouse + from the specified workspace using the provided WorkspaceId and WarehouseId. + +.PARAMETER WorkspaceId + The unique identifier of the workspace from which the warehouse will be removed. + +.PARAMETER WarehouseId + The unique identifier of the warehouse to be removed. + +.EXAMPLE + Remove-FabricWarehouse -WorkspaceId "workspace-12345" -WarehouseId "warehouse-67890" + This example removes the warehouse with ID "warehouse-67890" from the workspace with ID "workspace-12345". + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch +#> +function Remove-FabricWarehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WarehouseId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/warehouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $WarehouseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Warehouse '$WarehouseId' deleted successfully from workspace '$WorkspaceId'." -Level Info + + } + catch { + # Step 5: Log and handle errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to delete Warehouse '$WarehouseId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Warehouse/Update-FabricWarehouse.ps1 b/powershell/FabricACEToolkit/Public/Warehouse/Update-FabricWarehouse.ps1 new file mode 100644 index 0000000..8b84031 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Warehouse/Update-FabricWarehouse.ps1 @@ -0,0 +1,105 @@ +<# +.SYNOPSIS + Updates an existing warehouse in a specified Microsoft Fabric workspace. + +.DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update an existing warehouse + in the specified workspace. It supports optional parameters for warehouse description. + +.PARAMETER WorkspaceId + The unique identifier of the workspace where the warehouse exists. This parameter is optional. + +.PARAMETER WarehouseId + The unique identifier of the warehouse to be updated. This parameter is mandatory. + +.PARAMETER WarehouseName + The new name of the warehouse. This parameter is mandatory. + +.PARAMETER WarehouseDescription + An optional new description for the warehouse. + +.EXAMPLE + Update-FabricWarehouse -WorkspaceId "workspace-12345" -WarehouseId "warehouse-67890" -WarehouseName "Updated Warehouse" -WarehouseDescription "Updated description" + This example updates the warehouse with ID "warehouse-67890" in the workspace with ID "workspace-12345" with a new name and description. + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Test-TokenExpired` to ensure token validity before making the API request. + + Author: Tiago Balabuch + +#> +function Update-FabricWarehouse { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WarehouseId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$WarehouseName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WarehouseDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/warehouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $WarehouseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $WarehouseName + } + + if ($WarehouseDescription) { + $body.description = $WarehouseDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Warehouse '$WarehouseName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Warehouse. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 new file mode 100644 index 0000000..cc04243 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 @@ -0,0 +1,101 @@ +<# +.SYNOPSIS +Provisions an identity for a Fabric workspace. + +.DESCRIPTION +The `Add-FabricWorkspaceIdentity` function provisions an identity for a specified workspace by making an API call. + +.PARAMETER WorkspaceId +The unique identifier of the workspace for which the identity will be provisioned. + +.EXAMPLE +Add-FabricWorkspaceIdentity -WorkspaceId "workspace123" + +Provisions a Managed Identity for the workspace with ID "workspace123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Add-FabricWorkspaceIdentity { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/provisionIdentity" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Workspace identity was successfully provisioned for workspace '$WorkspaceId'." -Level Info + return $response + } + 202 { + Write-Message -Message "Workspace identity provisioning accepted for workspace '$WorkspaceId'. Provisioning in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + [string]$location = $responseHeader["Location"] + [string]$retryAfter = $responseHeader["Retry-After"] + + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Location: '$location'" -Level Debug + Write-Message -Message "Retry-After: '$retryAfter'" -Level Debug + + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 5: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to provision workspace identity. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 new file mode 100644 index 0000000..4d29053 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 @@ -0,0 +1,112 @@ +<# +.SYNOPSIS +Assigns a role to a principal for a specified Fabric workspace. + +.DESCRIPTION +The `Add-FabricWorkspaceRoleAssignments` function assigns a role (e.g., Admin, Contributor, Member, Viewer) to a principal (e.g., User, Group, ServicePrincipal) in a Fabric workspace by making a POST request to the API. + +.PARAMETER WorkspaceId +The unique identifier of the workspace. + +.PARAMETER PrincipalId +The unique identifier of the principal (User, Group, etc.) to assign the role. + +.PARAMETER PrincipalType +The type of the principal. Allowed values: Group, ServicePrincipal, ServicePrincipalProfile, User. + +.PARAMETER WorkspaceRole +The role to assign to the principal. Allowed values: Admin, Contributor, Member, Viewer. + +.EXAMPLE +Add-FabricWorkspaceRoleAssignment -WorkspaceId "workspace123" -PrincipalId "principal123" -PrincipalType "User" -WorkspaceRole "Admin" + +Assigns the Admin role to the user with ID "principal123" in the workspace "workspace123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Add-FabricWorkspaceRoleAssignment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$PrincipalId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Group', 'ServicePrincipal', 'ServicePrincipalProfile', 'User')] + [string]$PrincipalType, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Admin', 'Contributor', 'Member', 'Viewer')] + [string]$WorkspaceRole + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/roleAssignments" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + principal = @{ + id = $PrincipalId + type = $PrincipalType + } + role = $WorkspaceRole + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 4 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 201) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle empty response + if (-not $response) { + Write-Message -Message "No data returned from the API." -Level Warning + return $null + } + + Write-Message -Message "Role '$WorkspaceRole' assigned to principal '$PrincipalId' successfully in workspace '$WorkspaceId'." -Level Info + return $response + + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to assign role. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Assign-FabricWorkspaceCapacity.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Assign-FabricWorkspaceCapacity.ps1 new file mode 100644 index 0000000..0754a94 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Assign-FabricWorkspaceCapacity.ps1 @@ -0,0 +1,83 @@ +<# +.SYNOPSIS +Assigns a Fabric workspace to a specified capacity. + +.DESCRIPTION +The `Assign-FabricWorkspaceCapacity` function sends a POST request to assign a workspace to a specific capacity. + +.PARAMETER WorkspaceId +The unique identifier of the workspace to be assigned. + +.PARAMETER CapacityId +The unique identifier of the capacity to which the workspace should be assigned. + +.EXAMPLE +Assign-FabricWorkspaceCapacity -WorkspaceId "workspace123" -CapacityId "capacity456" + +Assigns the workspace with ID "workspace123" to the capacity "capacity456". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Assign-FabricWorkspaceCapacity { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$CapacityId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/assignToCapacity" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + capacityId = $CapacityId + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 4 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 202) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + Write-Message -Message "Successfully assigned workspace with ID '$WorkspaceId' to capacity with ID '$CapacityId'." -Level Info + } + catch { + # Step 6: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to assign workspace with ID '$WorkspaceId' to capacity with ID '$CapacityId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Get-FabricWorkspace.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Get-FabricWorkspace.ps1 new file mode 100644 index 0000000..7779700 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Get-FabricWorkspace.ps1 @@ -0,0 +1,149 @@ +<# +.SYNOPSIS +Retrieves details of a Microsoft Fabric workspace by its ID or name. + +.DESCRIPTION +The `Get-FabricWorkspace` function fetches workspace details from the Fabric API. It supports filtering by WorkspaceId or WorkspaceName. + +.PARAMETER WorkspaceId +The unique identifier of the workspace to retrieve. + +.PARAMETER WorkspaceName +The display name of the workspace to retrieve. + +.EXAMPLE +Get-FabricWorkspace -WorkspaceId "workspace123" + +Fetches details of the workspace with ID "workspace123". + +.EXAMPLE +Get-FabricWorkspace -WorkspaceName "MyWorkspace" + +Fetches details of the workspace with the name "MyWorkspace". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. +- Returns the matching workspace details or all workspaces if no filter is provided. + +Author: Tiago Balabuch +#> + +function Get-FabricWorkspace { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$WorkspaceName + ) + + try { + # Step 1: Handle ambiguous input + if ($WorkspaceId -and $WorkspaceName) { + Write-Message -Message "Both 'WorkspaceId' and 'WorkspaceName' were provided. Please specify only one." -Level Error + return $null + } + + # Step 2: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $workspaces = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces" -f $FabricConfig.BaseUrl + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $workspaces += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + + # Step 8: Filter results based on provided parameters + $workspace = if ($WorkspaceId) { + $workspaces | Where-Object { $_.Id -eq $WorkspaceId } + } + elseif ($WorkspaceName) { + $workspaces | Where-Object { $_.DisplayName -eq $WorkspaceName } + } + else { + # Return all workspaces if no filter is provided + Write-Message -Message "No filter provided. Returning all workspaces." -Level Debug + $workspaces + } + + # Step 9: Handle results + if ($workspace) { + Write-Message -Message "Workspace found matching the specified criteria." -Level Debug + return $workspace + } + else { + Write-Message -Message "No workspace found matching the provided criteria." -Level Warning + return $null + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve workspace. Error: $errorDetails" -Level Error + } +} \ No newline at end of file diff --git a/powershell/FabricACEToolkit/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 new file mode 100644 index 0000000..02b2f58 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 @@ -0,0 +1,153 @@ +<# +.SYNOPSIS +Retrieves role assignments for a specified Fabric workspace. + +.DESCRIPTION +The `Get-FabricWorkspaceRoleAssignments` function fetches the role assignments associated with a Fabric workspace by making a GET request to the API. If `WorkspaceRoleAssignmentId` is provided, it retrieves the specific role assignment. + +.PARAMETER WorkspaceId +The unique identifier of the workspace to fetch role assignments for. + +.PARAMETER WorkspaceRoleAssignmentId +(Optional) The unique identifier of a specific role assignment to retrieve. + +.EXAMPLE +Get-FabricWorkspaceRoleAssignments -WorkspaceId "workspace123" + +Fetches all role assignments for the workspace with the ID "workspace123". + +.EXAMPLE +Get-FabricWorkspaceRoleAssignments -WorkspaceId "workspace123" -WorkspaceRoleAssignmentId "role123" + +Fetches the role assignment with the ID "role123" for the workspace "workspace123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Get-FabricWorkspaceRoleAssignment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceRoleAssignmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 3: Initialize variables + $continuationToken = $null + $workspaceRoles = @() + + if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { + Add-Type -AssemblyName System.Web + } + + # Step 4: Loop to retrieve all capacities with continuation token + Write-Message -Message "Loop started to get continuation token" -Level Debug + $baseApiEndpointUrl = "{0}/workspaces/{1}/roleAssignments" -f $FabricConfig.BaseUrl, $WorkspaceId + + do { + # Step 5: Construct the API URL + $apiEndpointUrl = $baseApiEndpointUrl + + if ($null -ne $continuationToken) { + # URL-encode the continuation token + $encodedToken = [System.Web.HttpUtility]::UrlEncode($continuationToken) + $apiEndpointUrl = "{0}?continuationToken={1}" -f $apiEndpointUrl, $encodedToken + } + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 6: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Get ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 7: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message -Message "Error Details: $($response.moreDetails)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 8: Add data to the list + if ($null -ne $response) { + Write-Message -Message "Adding data to the list" -Level Debug + $workspaceRoles += $response.value + + # Update the continuation token if present + if ($response.PSObject.Properties.Match("continuationToken")) { + Write-Message -Message "Updating the continuation token" -Level Debug + $continuationToken = $response.continuationToken + Write-Message -Message "Continuation token: $continuationToken" -Level Debug + } + else { + Write-Message -Message "Updating the continuation token to null" -Level Debug + $continuationToken = $null + } + } + else { + Write-Message -Message "No data received from the API." -Level Warning + break + } + } while ($null -ne $continuationToken) + Write-Message -Message "Loop finished and all data added to the list" -Level Debug + # Step 8: Filter results based on provided parameters + $roleAssignments = if ($WorkspaceRoleAssignmentId) { + $workspaceRoles | Where-Object { $_.Id -eq $WorkspaceRoleAssignmentId } + } + else { + $workspaceRoles + } + + # Step 9: Handle results + if ($roleAssignments) { + Write-Message -Message "Found $($roleAssignments.Count) role assignments for WorkspaceId '$WorkspaceId'." -Level Debug + # Transform data into custom objects + $results = foreach ($obj in $roleAssignments) { + [PSCustomObject]@{ + ID = $obj.id + PrincipalId = $obj.principal.id + DisplayName = $obj.principal.displayName + Type = $obj.principal.type + UserPrincipalName = $obj.principal.userDetails.userPrincipalName + aadAppId = $obj.principal.servicePrincipalDetails.aadAppId + Role = $obj.role + } + } + return $results + } + else { + if ($WorkspaceRoleAssignmentId) { + Write-Message -Message "No role assignment found with ID '$WorkspaceRoleAssignmentId' for WorkspaceId '$WorkspaceId'." -Level Warning + } + else { + Write-Message -Message "No role assignments found for WorkspaceId '$WorkspaceId'." -Level Warning + } + return @() + } + } + catch { + # Step 10: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve role assignments for WorkspaceId '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/New-FabricWorkspace.ps1 b/powershell/FabricACEToolkit/Public/Workspace/New-FabricWorkspace.ps1 new file mode 100644 index 0000000..4da2489 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/New-FabricWorkspace.ps1 @@ -0,0 +1,122 @@ +<# +.SYNOPSIS +Creates a new Fabric workspace with the specified display name. + +.DESCRIPTION +The `Add-FabricWorkspace` function creates a new workspace in the Fabric platform by sending a POST request to the API. It validates the display name and handles both success and error responses. + +.PARAMETER WorkspaceName +The display name of the workspace to be created. Must only contain alphanumeric characters, spaces, and underscores. + +.EXAMPLE +Add-FabricWorkspace -WorkspaceName "NewWorkspace" + +Creates a workspace named "NewWorkspace". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function New-FabricWorkspace { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$WorkspaceName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$CapacityId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces" -f $FabricConfig.BaseUrl + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $WorkspaceName + } + + if ($WorkspaceDescription) { + $body.description = $WorkspaceDescription + } + + if ($CapacityId) { + $body.capacityId = $CapacityId + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 2 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Handle and log the response + switch ($statusCode) { + 201 { + Write-Message -Message "Workspace '$WorkspaceName' created successfully!" -Level Info + return $response + } + 202 { + Write-Message -Message "Workspace '$WorkspaceName' creation accepted. Provisioning in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 6: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create workspace. Error: $errorDetails" -Level Error + + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspace.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspace.ps1 new file mode 100644 index 0000000..d65a2be --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspace.ps1 @@ -0,0 +1,68 @@ +<# +.SYNOPSIS +Deletes an existing Fabric workspace by its workspace ID. + +.DESCRIPTION +The `Remove-FabricWorkspace` function deletes a workspace in the Fabric platform by sending a DELETE request to the API. It validates the workspace ID and handles both success and error responses. + +.PARAMETER WorkspaceId +The unique identifier of the workspace to be deleted. + +.EXAMPLE +Remove-FabricWorkspace -WorkspaceId "workspace123" + +Deletes the workspace with the ID "workspace123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> +function Remove-FabricWorkspace { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Workspace '$WorkspaceId' deleted successfully!" -Level Info + return $null + + } + catch { + # Step 5: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve capacity. Error: $errorDetails" -Level Error + return $null + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 new file mode 100644 index 0000000..2a55d5d --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 @@ -0,0 +1,94 @@ +<# +.SYNOPSIS +Deprovisions the Managed Identity for a specified Fabric workspace. + +.DESCRIPTION +The `Remove-FabricWorkspaceCapacity` function deprovisions the Managed Identity from the given workspace by calling the appropriate API endpoint. + +.PARAMETER WorkspaceId +The unique identifier of the workspace from which the identity will be removed. + +.EXAMPLE +Remove-FabricWorkspaceCapacity -WorkspaceId "workspace123" + +Deprovisions the Managed Identity for the workspace with ID "workspace123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Remove-FabricWorkspaceIdentity { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/deprovisionIdentity" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Handle and log the response + switch ($statusCode) { + 200 { + Write-Message -Message "Workspace identity was successfully deprovisioned for workspace '$WorkspaceId'." -Level Info + return $response.value + } + 202 { + Write-Message -Message "Workspace identity deprovisioning accepted for workspace '$WorkspaceId'. Deprovisioning in progress!" -Level Info + [string]$operationId = $responseHeader["x-ms-operation-id"] + Write-Message -Message "Operation ID: '$operationId'" -Level Debug + Write-Message -Message "Getting Long Running Operation status" -Level Debug + + $operationStatus = Get-FabricLongRunningOperation -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationStatus" -Level Debug + # Handle operation result + if ($operationStatus.status -eq "Succeeded") { + Write-Message -Message "Operation Succeeded" -Level Debug + Write-Message -Message "Getting Long Running Operation result" -Level Debug + + $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId + Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + + return $operationResult + } + else { + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Debug + Write-Message -Message "Operation failed. Status: $($operationStatus)" -Level Error + return $operationStatus + } + } + default { + Write-Message -Message "Unexpected response code: $statusCode" -Level Error + Write-Message -Message "Error details: $($response.message)" -Level Error + throw "API request failed with status code $statusCode." + } + } + } + catch { + # Step 5: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to deprovision workspace identity. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 new file mode 100644 index 0000000..36be3a1 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 @@ -0,0 +1,74 @@ +<# +.SYNOPSIS +Removes a role assignment from a Fabric workspace. + +.DESCRIPTION +The `Remove-FabricWorkspaceRoleAssignment` function deletes a specific role assignment from a Fabric workspace by making a DELETE request to the API. + +.PARAMETER WorkspaceId +The unique identifier of the workspace. + +.PARAMETER WorkspaceRoleAssignmentId +The unique identifier of the role assignment to be removed. + +.EXAMPLE +Remove-FabricWorkspaceRoleAssignment -WorkspaceId "workspace123" -WorkspaceRoleAssignmentId "role123" + +Removes the role assignment with the ID "role123" from the workspace "workspace123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch + +#> + +function Remove-FabricWorkspaceRoleAssignment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceRoleAssignmentId + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/roleAssignments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $WorkspaceRoleAssignmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Delete ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 4: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Role assignment '$WorkspaceRoleAssignmentId' successfully removed from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to remove role assignments for WorkspaceId '$WorkspaceId'. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Unassign-FabricWorkspaceCapacity.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Unassign-FabricWorkspaceCapacity.ps1 new file mode 100644 index 0000000..8c8ce8b --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Unassign-FabricWorkspaceCapacity.ps1 @@ -0,0 +1,67 @@ +<# +.SYNOPSIS +Unassigns a Fabric workspace from its capacity. + +.DESCRIPTION +The `Unassign-FabricWorkspaceCapacity` function sends a POST request to unassign a workspace from its assigned capacity. + +.PARAMETER WorkspaceId +The unique identifier of the workspace to be unassigned from its capacity. + +.EXAMPLE +Unassign-FabricWorkspaceCapacity -WorkspaceId "workspace123" + +Unassigns the workspace with ID "workspace123" from its capacity. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Unassign-FabricWorkspaceCapacity { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId + ) + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/unassignFromCapacity" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Message + + # Step 3: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Post ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + + # Step 4: Validate the response code + if ($statusCode -ne 202) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + Write-Message -Message "Workspace capacity has been successfully unassigned from workspace '$WorkspaceId'." -Level Info + } + catch { + # Step 5: Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to unassign workspace from capacity. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Update-FabricWorkspace.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Update-FabricWorkspace.ps1 new file mode 100644 index 0000000..77b1056 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Update-FabricWorkspace.ps1 @@ -0,0 +1,103 @@ +<# +.SYNOPSIS +Updates the properties of a Fabric workspace. + +.DESCRIPTION +The `Update-FabricWorkspace` function updates the name and/or description of a specified Fabric workspace by making a PATCH request to the API. + +.PARAMETER WorkspaceId +The unique identifier of the workspace to be updated. + +.PARAMETER WorkspaceName +The new name for the workspace. + +.PARAMETER WorkspaceDescription +(Optional) The new description for the workspace. + +.EXAMPLE +Update-FabricWorkspace -WorkspaceId "workspace123" -WorkspaceName "NewWorkspaceName" + +Updates the name of the workspace with the ID "workspace123" to "NewWorkspaceName". + +.EXAMPLE +Update-FabricWorkspace -WorkspaceId "workspace123" -WorkspaceName "NewName" -WorkspaceDescription "Updated description" + +Updates both the name and description of the workspace "workspace123". + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Update-FabricWorkspace { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidatePattern('^[a-zA-Z0-9_ ]*$')] + [string]$WorkspaceName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceDescription + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Step 3: Construct the request body + $body = @{ + displayName = $WorkspaceName + } + + if ($WorkspaceDescription) { + $body.description = $WorkspaceDescription + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle results + Write-Message -Message "Workspace '$WorkspaceName' updated successfully!" -Level Info + return $response + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update workspace. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 b/powershell/FabricACEToolkit/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 new file mode 100644 index 0000000..f619e46 --- /dev/null +++ b/powershell/FabricACEToolkit/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 @@ -0,0 +1,104 @@ +<# +.SYNOPSIS +Updates the role assignment for a specific principal in a Fabric workspace. + +.DESCRIPTION +The `Update-FabricWorkspaceRoleAssignment` function updates the role assigned to a principal in a workspace by making a PATCH request to the API. + +.PARAMETER WorkspaceId +The unique identifier of the workspace where the role assignment exists. + +.PARAMETER WorkspaceRoleAssignmentId +The unique identifier of the role assignment to be updated. + +.PARAMETER WorkspaceRole +The new role to assign to the principal. Must be one of the following: +- Admin +- Contributor +- Member +- Viewer + +.EXAMPLE +Update-FabricWorkspaceRoleAssignment -WorkspaceId "workspace123" -WorkspaceRoleAssignmentId "assignment456" -WorkspaceRole "Admin" + +Updates the role assignment to "Admin" for the specified workspace and role assignment. + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Test-TokenExpired` to ensure token validity before making the API request. + +Author: Tiago Balabuch +#> + +function Update-FabricWorkspaceRoleAssignment { + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceRoleAssignmentId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [ValidateSet('Admin', 'Contributor', 'Member', 'Viewer')] + [string]$WorkspaceRole + ) + + try { + # Step 1: Ensure token validity + Write-Message -Message "Validating token..." -Level Debug + Test-TokenExpired + Write-Message -Message "Token validation completed." -Level Debug + + # Step 2: Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/roleAssignments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $WorkspaceRoleAssignmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Message + + # Step 3: Construct the request body + $body = @{ + role = $WorkspaceRole + } + + # Convert the body to JSON + $bodyJson = $body | ConvertTo-Json -Depth 4 -Compress + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + # Step 4: Make the API request + $response = Invoke-RestMethod ` + -Headers $FabricConfig.FabricHeaders ` + -Uri $apiEndpointUrl ` + -Method Patch ` + -Body $bodyJson ` + -ContentType "application/json" ` + -ErrorAction Stop ` + -SkipHttpErrorCheck ` + -ResponseHeadersVariable "responseHeader" ` + -StatusCodeVariable "statusCode" + + # Step 5: Validate the response code + if ($statusCode -ne 200) { + Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error + Write-Message -Message "Error: $($response.message)" -Level Error + Write-Message "Error Code: $($response.errorCode)" -Level Error + return $null + } + + # Step 6: Handle empty response + if (-not $response) { + Write-Message -Message "No data returned from the API." -Level Warning + return $null + } + + Write-Message -Message "Role assignment $WorkspaceRoleAssignmentId updated successfully in workspace '$WorkspaceId'." -Level Info + return $response + + } + catch { + # Step 7: Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update role assignment. Error: $errorDetails" -Level Error + } +} diff --git a/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceIdentity.md b/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceIdentity.md new file mode 100644 index 0000000..72434a6 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceIdentity.md @@ -0,0 +1,56 @@ +# Add-FabricWorkspaceIdentity + +## Overview + +The `Add-FabricWorkspaceIdentity` function provisions an identity for a specified workspace by making an API call. This helps manage workspace access and security in Microsoft Fabric. + +## Description + +This function sends a POST request to the Microsoft Fabric API to provision an identity for a specific workspace. It handles token validation, constructs the API URL, processes the API request, and handles long-running operations. + +## Features + +- Ensures token validity using `Test-TokenExpired` before making the API request. +- Dynamically constructs the API URL based on provided `WorkspaceId`. +- Handles the response, including long-running operations and retries. +- Logs errors for debugging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace for which the identity will be provisioned. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Provision a Workspace Identity + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Add-FabricWorkspaceIdentity -WorkspaceId $workspace.id +``` + +This example provisions a Managed Identity for the workspace with ID `workspace123`. + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Sends a POST request to the Microsoft Fabric API. +4. Handles API responses, including long-running operations and retries. + +## Error Handling + +- Logs detailed error messages for API request failures. +- Throws an exception if the API request fails unexpectedly. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceRoleAssignments.md b/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceRoleAssignments.md new file mode 100644 index 0000000..e01e996 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceRoleAssignments.md @@ -0,0 +1,77 @@ +# Add-FabricWorkspaceRoleAssignments + +## Overview + +The `Add-FabricWorkspaceRoleAssignments` function assigns a role (e.g., Admin, Contributor, Member, Viewer) to a principal (e.g., User, Group, ServicePrincipal) in a Fabric workspace by making a POST request to the API. + +## Description + +This function sends a POST request to the Microsoft Fabric API to assign a specified role to a given principal within a workspace. It handles token validation, constructs the API URL, processes the API request, and handles the response, including error scenarios. + +## Features + +- Ensures token validity using `Test-TokenExpired` before making the API request. +- Dynamically constructs the API URL based on provided `WorkspaceId`. +- Supports assigning roles to various types of principals (Group, ServicePrincipal, ServicePrincipalProfile, User). +- Logs errors for debugging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace. +- **Type:** String +- **Mandatory:** Yes + +### PrincipalId + +- **Description:** The unique identifier of the principal (User, Group, etc.) to assign the role. +- **Type:** String +- **Mandatory:** Yes + +### PrincipalType + +- **Description:** The type of the principal. Allowed values: Group, ServicePrincipal, ServicePrincipalProfile, User. +- **Type:** String +- **Mandatory:** Yes + +### WorkspaceRole + +- **Description:** The role to assign to the principal. Allowed values: Admin, Contributor, Member, Viewer. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Assign a Role to a Principal. The `PrincipalId` must be an EntraID. + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Add-FabricWorkspaceRoleAssignment ` +-WorkspaceId $workspace.id ` +-PrincipalId "111111111-11111-1111-1111-11111111111" ` +-PrincipalType User ` +-WorkspaceRole Viewer +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with principal and role details. +4. Sends a POST request to the Microsoft Fabric API. +5. Handles API responses, including success and error handling. + +## Error Handling + +- Logs detailed error messages for API request failures. +- Throws an exception if the API request fails unexpectedly. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByCapacity.md b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByCapacity.md new file mode 100644 index 0000000..3b4810e --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByCapacity.md @@ -0,0 +1,58 @@ +# Assign-FabricDomainWorkspaceByCapacity + +## Overview +The `Assign-FabricDomainWorkspaceByCapacity` function assigns workspaces to a domain based on specified capacity IDs within Microsoft Fabric. It validates token expiration, constructs the API request, handles long-running operations, and logs detailed steps. + +## Features + +- Validates authentication token using the `Test-TokenExpired` function. +- Supports assigning workspaces by capacities to a domain. +- Handles long-running operations and returns the final status. +- Provides robust logging for debugging and error handling. + +## Parameters + +### `DomainId` *(Mandatory)* +- **Description:** The ID of the domain where workspaces will be assigned. +- **Type:** String + +### `CapacitiesIds` *(Mandatory)* +- **Description:** An array of capacity IDs to assign workspaces. +- **Type:** Array + +## Usage Examples + +### Example 1: Assign Workspaces by Capacity to a Domain + +```powershell +Assign-FabricDomainWorkspaceByCapacity -DomainId "domain123" -CapacitiesIds @("capacity1", "capacity2") +``` + +Assigns workspaces to the domain with ID domain123 based on the specified capacity IDs. + +## Prerequisites +- A global `$FabricConfig` object with the following properties: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be available to check token validity. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL to assign workspaces by capacities +3. Sends a POST request to the API with the required request body. +4. Handles different status codes, including long-running operations. +5. Returns either the result of the operation or logs the error if the operation fails. + +## Error Handling + +- Logs error messages if the API request fails or if the operation encounters issues. +- In case of long-running operations, it checks the status and handles the operation result. + +## Notes + +- The function includes detailed logging for each major step in the process. +- Long-running operations are handled with the `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult` functions. + +## Author +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceById.md b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceById.md new file mode 100644 index 0000000..b8f7684 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceById.md @@ -0,0 +1,53 @@ +# Assign-FabricDomainWorkspaceById + +## Overview +The `Assign-FabricDomainWorkspaceById` function assigns multiple workspaces to a specified domain in Microsoft Fabric. It securely interacts with the Fabric API, ensuring token validation and robust error handling. + +## Features +- Validates the authentication token before initiating API requests. +- Allows batch assignment of workspaces using an array of workspace IDs. +- Handles API responses efficiently, including logging and error reporting. + +## Parameters + +### `DomainId` *(Required)* +- **Description:** The unique identifier of the domain where workspaces will be assigned. +- **Type:** String + +### `WorkspaceIds` *(Required)* +- **Description:** An array of workspace IDs to be assigned to the specified domain. +- **Type:** Array of Strings + +## Example Usage + +### Example 1: Assign Workspaces by Ids to a Domain + +```powershell +Assign-FabricDomainWorkspaceById -DomainId "domain12345" -WorkspaceIds @("workspace-12345", "workspace-67890", "workspace-02468") +``` + +Assigns the workspaces with IDs "ws1", "ws2", and "ws3" to the domain with ID "12345". + +## Prerequisites +- The global configuration variable `$FabricConfig` must be set, containing: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + + +## Key Workflow +1. **Token Validation:** Ensures that the authentication token is valid by invoking the `Test-TokenExpired` function. +2. **API Endpoint Construction:** Dynamically builds the API URL using the provided domain ID. +3. **Request Body Preparation:** Constructs the request payload with workspace IDs and converts it to JSON format. +4. **API Request Execution:** Sends a POST request to assign workspaces, logging any issues or unexpected responses. +5. **Response Validation:** Confirms that the API request was successful based on the status code. +6. **Error Handling:** Captures and logs errors, providing detailed diagnostic information. + +## Error Handling +- Logs descriptive error messages if token validation or API requests fail. +- Handles unexpected response codes gracefully by logging error details. +- Returns `null` in case of errors. + +## Author +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByPrincipal.md b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByPrincipal.md new file mode 100644 index 0000000..17016f6 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByPrincipal.md @@ -0,0 +1,70 @@ +# Assign-FabricDomainWorkspaceByPrincipal + +## Overview + +The `Assign-FabricDomainWorkspaceByPrincipal` function assigns workspaces to a domain in Microsoft Fabric using an array of principal IDs and their associated types. It validates the provided input, ensures token validity, and interacts with the Fabric API to perform the assignment. + +## Features + +- Accepts a structured array of principal IDs and types for assigning domain workspaces. +- Handles long-running operations with detailed logging. +- Validates the structure of principal objects to ensure correctness. +- Provides robust error handling and detailed logging at every step. + +## Parameters + +### `DomainId` *(Required)* + +- **Description:** The unique identifier of the domain where workspaces will be assigned. +- **Type:** String + +### `PrincipalIds` *(Required)* + +- **Description:** An array of objects representing principals, each containing: + - `id`: The unique identifier of the principal. + - `type`: The type of principal (e.g., "User"). +- **Type:** Array of Objects + +## Usage Examples + +### Example 1: Assign Workspaces by Capacity to a Domain + +```powershell +$PrincipalIds = @( @{id = "813abb4a-414c-4ac0-9c2c-bd17036fd58c"; type = "User" }, + @{id = "b5b9495c-685a-447a-b4d3-2d8e963e6288"; type = "User" }) + +$domain = Get-FabricDomain -DomainName "domain123" +Assign-FabricDomainWorkspaceByPrincipal -DomainId $domain.id -PrincipalIds $PrincipalIds +``` + +Assigns workspaces to the domain with ID domain123 based on the specified capacity IDs. + +## Prerequisites + +- A global `$FabricConfig` object with the following properties: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be available to check token validity. + +## Key Workflow + +1. **Input Validation:** Ensures each principal object contains the `id` and `type` keys. +2. **Token Validation:** Confirms token validity via `Test-TokenExpired`. +3. **API Endpoint Construction:** Dynamically generates the endpoint URL using the domain ID. +4. **Request Body Preparation:** Formats the `PrincipalIds` into the appropriate JSON structure. +5. **API Request Execution:** Sends a POST request to assign workspaces by principals, with detailed logging of responses. +6. **Response Handling:** + - Logs successful operations or tracks long-running operations via `Get-FabricLongRunningOperation`. + - Handles unexpected response codes gracefully, logging relevant details. +7. **Error Handling:** Captures and logs error details for troubleshooting. + +## Error Handling + +- Validates the structure of `PrincipalIds` and throws detailed errors for invalid inputs. +- Logs unexpected status codes or API failures with error details. +- Returns structured error information for failed API requests or operations. + +## Author + +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceRoleAssignment.md b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceRoleAssignment.md new file mode 100644 index 0000000..7a3b2d2 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceRoleAssignment.md @@ -0,0 +1,75 @@ +# Assign-FabricDomainWorkspaceRoleAssignment + +## Overview + +The `Assign-FabricDomainWorkspaceRoleAssignment` function allows bulk assignment of roles to principals within a specified domain in Microsoft Fabric. The function validates input, ensures token validity, and interacts with the Fabric API to execute the assignments. + +## Features + +- Supports role assignment for two types of roles: `Admins` and `Contributors`. +- Ensures all principals have valid `id` and `type` properties. +- Validates token expiration before making API requests. +- Logs detailed information about the API request, response, and errors. + +## Parameters + +### `DomainId` *(Required)* + +- **Description:** The unique identifier of the Fabric domain where roles will be assigned. +- **Type:** String + +### `DomainRole` *(Required)* + +- **Description:** The role to assign to the principals. Accepted values: + - `Admins` + - `Contributors` +- **Type:** String + +### `PrincipalIds` *(Required)* + +- **Description:** An array of objects representing principals. Each principal must include: + - `id`: The unique identifier of the principal. + - `type`: The type of the principal (e.g., `User`, `Group`). +- **Type:** Array of objects + +## Usage Examples + +### Example 1: Assigns the `Admins` role to the specified principals in the domain with ID "12345". + +```powershell +Assign-FabricDomainWorkspaceRoleAssignment ` + -DomainId "domain12345" ` + -DomainRole "Admins" ` + -PrincipalIds @(@{id = "user1"; type = "User"}, @{id = "group1"; type = "Group"}) +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. +- The `Write-Message` helper function must be available for consistent logging. + +## Key Workflow + +1. **Input Validation:** Ensures each principal object contains `id` and `type` properties. +2. **Token Validation:** Calls `Test-TokenExpired` to confirm the token is valid. +3. **API URL Construction:** Dynamically creates the API endpoint using the domain ID. +4. **Request Body Preparation:** Formats the `DomainRole` and `PrincipalIds` into JSON. +5. **API Request Execution:** Sends a POST request to the API endpoint for role assignment. +6. **Response Handling:** + - Logs and verifies the response status code. + - Handles unexpected response codes and logs error details. +7. **Error Handling:** Catches and logs exceptions with detailed error messages. + +This example assigns the Admins role to two principals: a user with ID user1 and a group with ID group1, in the domain with ID 12345. + +## Error Handling + +- Logs unexpected API responses with error messages and codes. +- Catches and displays detailed error messages for debugging. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Assign-FabricWorkspaceCapacity.md b/powershell/FabricACEToolkit/docs/Assign-FabricWorkspaceCapacity.md new file mode 100644 index 0000000..2f50360 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Assign-FabricWorkspaceCapacity.md @@ -0,0 +1,62 @@ +# Assign-FabricWorkspaceCapacity + +## Overview + +The `Assign-FabricWorkspaceCapacity` function sends a POST request to assign a workspace to a specific capacity. + +## Description + +This function assigns a specified workspace to a given capacity in Microsoft Fabric. It handles token validation, constructs the API request, and processes the API response. + +## Features + +- Validates authentication token using the `Test-TokenExpired` function. +- Constructs the API URL dynamically based on `WorkspaceId`. +- Supports assigning a workspace to a specific capacity. +- Logs detailed steps for debugging and error handling. + +## Parameters + +### `WorkspaceId` *(Mandatory)* + +- **Description:** The unique identifier of the workspace to be assigned. +- **Type:** String + +### `CapacityId` *(Mandatory)* + +- **Description:** The unique identifier of the capacity to which the workspace should be assigned. +- **Type:** String + +## Usage Examples + +### Example 1: Assign a workspace to a capacity + +```powershell +$capacity = Get-FabricCapacity -capacityName "capacity-45678" +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Assign-FabricWorkspaceCapacity -WorkspaceId $workspace.id -CapacityId $capacity.id +``` + +## Prerequisites + +- A global `$FabricConfig` object must be configured with the following properties: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be available to check token validity. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL to assign the workspace to the capacity. +3. Sends a POST request to the API with the required request body. +4. Handles different status codes, including long-running operations. +5. Returns either the result of the operation or logs the error if the operation fails. + +## Error Handling + +- Logs error messages if the API request fails or if the operation encounters issues. +- The function includes detailed logging for each major step in the process. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Convert-FromBase64.md b/powershell/FabricACEToolkit/docs/Convert-FromBase64.md new file mode 100644 index 0000000..feb4688 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Convert-FromBase64.md @@ -0,0 +1,59 @@ +# Convert-FromBase64 + +## Overview + +The `Convert-FromBase64` function decodes a Base64-encoded string into its original text representation. It is commonly used to reverse Base64 encoding applied to text or other data. + +## Features + +- Decodes Base64 strings into UTF-8 text. +- Provides descriptive error handling and logging for decoding issues. + +## Parameters + +### Base64String + +- **Description:** The Base64-encoded string to decode. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Decode a Base64 string + +```powershell +Convert-FromBase64 -Base64String "SGVsbG8sIFdvcmxkIQ==" + +# Output: +# Hello, World! +``` + +### Example 2: Decode a Base64 string stored in a variable + +```powershell +$encodedString = "U29tZSBlbmNvZGVkIHRleHQ=" +Convert-FromBase64 -Base64String $encodedString + +# Output: +# Some encoded text +``` + +## Prerequisites + +- Assumes the Base64 input is a valid UTF-8 encoded string. +- Requires `Write-Message` for descriptive logging during error handling. + +## Key Workflow + +1. Converts the Base64 string to a byte array using `[Convert]::FromBase64String`. +2. Converts the byte array to a UTF-8 encoded string. +3. Returns the decoded string or throws an error if decoding fails. + +## Error Handling + +- Logs descriptive error messages if the decoding process fails. +- Throws exceptions for invalid input or decoding errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Convert-ToBase64.md b/powershell/FabricACEToolkit/docs/Convert-ToBase64.md new file mode 100644 index 0000000..d61a0f6 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Convert-ToBase64.md @@ -0,0 +1,58 @@ +# Convert-ToBase64 + +## Overview + +The `Convert-ToBase64` function encodes the content of a file into a Base64-encoded string. This is particularly useful for embedding binary data (e.g., images, documents) in text-based formats such as JSON or XML. + +## Features + +- Encodes file content into Base64 strings. +- Provides descriptive error handling and logging for encoding issues. + +## Parameters + +### filePath + +- **Description:** The full path to the file whose contents you want to encode into Base64. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Encode a file into a Base64 string + +```powershell +Convert-ToBase64 -filePath "C:\Path\To\File.txt" + +# Output: +# VGhpcyBpcyBhbiBlbmNvZGVkIGZpbGUu +``` + +### Example 2: Save encoded content to a file + +```powershell +$encodedContent = Convert-ToBase64 -filePath "C:\Path\To\Image.jpg" +$encodedContent | Set-Content -Path "C:\Path\To\EncodedImage.txt" + +# This saves the Base64-encoded content of the image to a text file. +``` + +## Prerequisites + +- Ensure the file exists at the specified path before running this function. +- Large files may cause memory constraints due to full loading into memory. + +## Key Workflow + +1. Reads the content of the specified file as a byte array using `[System.IO.File]::ReadAllBytes`. +2. Converts the byte array to a Base64 string using `[Convert]::ToBase64String`. +3. Returns the encoded string or throws an error if the process fails. + +## Error Handling + +- Logs descriptive error messages if the encoding process fails. +- Throws exceptions for invalid input or file access issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricCapacity.md b/powershell/FabricACEToolkit/docs/Get-FabricCapacity.md new file mode 100644 index 0000000..4d78105 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricCapacity.md @@ -0,0 +1,62 @@ +# Get-FabricCapacity + +## Overview +The `Get-FabricCapacity` function retrieves detailed information about capacities in a Microsoft Fabric workspace. It simplifies interaction with the Fabric API, offering options to query by `capacityId` or `capacityName`. + +## Features +- Handles token validation to ensure secure API access. +- Supports filtering by capacity ID or name. +- Automatically retrieves paginated data using continuation tokens. +- Provides error handling for robust operation. + +## Parameters + +### `capacityId` *(Optional)* +- **Description:** The unique identifier for the capacity. +- **Type:** String + +### `capacityName` *(Optional)* +- **Description:** The display name of the capacity. +- **Type:** String + +> **Note:** Only one parameter, `capacityId` or `capacityName`, should be specified at a time. + +## Usage Examples + +### Example 1: Retrieve Capacity by ID +```powershell +Get-FabricCapacity -capacityId "6b3297a9-84d0-4f51-99ac-919da2572ba4" +``` +Fetches details of the capacity with the specified ID. + +### Example 2: Retrieve Capacity by Name +```powershell +Get-FabricCapacity -capacityName "MyCapacity" +``` +Fetches details of the capacity with the specified name. + +### Example 3: List All Capacities +```powershell +Get-FabricCapacity +``` +Returns a list of all capacities available in the workspace. + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig` , containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow +1. Validates that only one input parameter (`capacityId` or `capacityName`) is provided. +2. Ensures the authentication token is valid. +3. Retrieves capacities via the Fabric API, handling paginated responses automatically. +4. Filters results based on provided criteria or returns all capacities if no filters are applied. + +## Error Handling +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Get-FabricDashboard.md b/powershell/FabricACEToolkit/docs/Get-FabricDashboard.md new file mode 100644 index 0000000..6182488 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricDashboard.md @@ -0,0 +1,45 @@ +# Get-FabricDashboard + +## Overview +The `Get-FabricDashboard` function retrieves all dashboards from a specified Microsoft Fabric workspace. This function ensures token validity, handles paginated API responses, and returns a consolidated list of dashboards. + +## Features +- Validates authentication token using the `Test-TokenExpired` function. +- Supports retrieval of all dashboards for a given workspace. +- Handles paginated responses via continuation tokens. +- Includes robust error handling and logging. + +## Parameters + +### `WorkspaceId` *(Mandatory)* +- **Description:** The ID of the workspace from which dashboards are retrieved. +- **Type:** String + +## Usage Examples + +### Example 1: Retrieve Dashboards from a Workspace +```powershell +Get-FabricDashboard -WorkspaceId "workspace-12345" +``` +Retrieves all dashboards from the workspace with ID `workspace-12345`. + +## Prerequisites +- A global `$FabricConfig` object with the following properties: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be available to check token validity. + +## Key Workflow +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL for retrieving dashboards. +3. Sends API requests, handling paginated responses with continuation tokens. +4. Processes and consolidates the response data into a single list. +5. Returns the list of dashboards. + +## Error Handling +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` in case of any errors during execution. + +## Author +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Get-FabricDataPipeline.md b/powershell/FabricACEToolkit/docs/Get-FabricDataPipeline.md new file mode 100644 index 0000000..370f6b6 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricDataPipeline.md @@ -0,0 +1,60 @@ +# Get-FabricDataPipeline + +## Overview +The `Get-FabricDataPipeline` function retrieves all data pipelines from a specified workspace using either the provided DataPipelineId or DataPipelineName. It validates the token, constructs the API URL, sends the API request, and processes the response. + +## Parameters + +### `WorkspaceId` *(Mandatory)* +- **Description:** The unique identifier of the workspace where the Data Pipeline exists. +- **Type:** String + +### `DataPipelineId` *(Mandatory)* +- **Description:** The unique identifier of the Data Pipeline to retrieve. +- **Type:** String + +### `DataPipelineName` *(Optional)* +- **Description:** The display name of the Data Pipeline. +- **Type:** String + +> **Note:** Only one parameter, `DataPipelineId` or `DataPipelineName`, should be specified at a time. + +## Usage Examples + +### Example 1: Retrieve Data Pipeline by ID +```powershell +Get-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineId "datapipeline-67890" +``` +Retrieves the Data Pipeline details for the Data Pipeline with ID `datapipeline-67890` in the workspace with ID `workspace-12345`. + +### Example 2: Retrieve Data Pipeline by Name +```powershell +Get-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineName "My Data Pipeline" +``` +Retrieves the Data Pipeline details for the Data Pipeline named `My Data Pipeline` in the workspace with ID `workspace-12345`. + +### Example 3: List all Data Pipeline in the workspace +```powershell +Get-FabricDataPipeline -WorkspaceId "workspace-12345" +``` +Returns a list of all Data Pipelines available in the workspace. + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig` , containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow +1. Validates that only one input parameter (`DataPipelineId` or `DataPipelineName`) is provided. +2. Ensures the authentication token is valid. +3. Retrieves capacities via the Fabric API, handling paginated responses automatically. +4. Filters results based on provided criteria or returns all capacities if no filters are applied. + +## Notes +- Requires a `$FabricConfig` global configuration object, including `BaseUrl` and `FabricHeaders`. +- Calls the `Test-TokenExpired` function to ensure token validity before making the API request. + +## Author +**Author**: Tiago Balabuch + diff --git a/powershell/FabricACEToolkit/docs/Get-FabricDatamart.md b/powershell/FabricACEToolkit/docs/Get-FabricDatamart.md new file mode 100644 index 0000000..4e14660 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricDatamart.md @@ -0,0 +1,49 @@ +# Get-FabricDatamart + +## Overview +The `Get-FabricDatamart` function retrieves all datamarts from a specified Microsoft Fabric workspace. This function ensures token validity, handles paginated API responses, and returns a consolidated list of datamarts . + +## Features +- Validates authentication token using the `Test-TokenExpired` function. +- Supports retrieval of all datamarts for a given workspace. +- Handles paginated responses via continuation tokens. +- Includes robust error handling and logging. + +## Parameters + +### `WorkspaceId` *(Mandatory)* +- **Description:** The ID of the workspace from which datamarts are retrieved. +- **Type:** String + +## Usage Examples + +### Example 1: Retrieve datamarts from a Workspace +```powershell +Get-FabricDatamart -WorkspaceId "workspace-12345" +``` +Retrieves all datamarts from the workspace with ID `workspace-12345`. + +## Prerequisites +- A global `$FabricConfig` object with the following properties: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be available to check token validity. + +## Key Workflow +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL for retrieving datamarts . +3. Sends API requests, handling paginated responses with continuation tokens. +4. Processes and consolidates the response data into a single list. +5. Returns the list of datamarts. + +## Error Handling +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` in case of any errors during execution. + +## Notes +- The function uses `System.Web.HttpUtility` to URL-encode continuation tokens. +- Continuation tokens are updated dynamically to fetch all paginated data. + +## Author +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Get-FabricDomain.md b/powershell/FabricACEToolkit/docs/Get-FabricDomain.md new file mode 100644 index 0000000..6eda603 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricDomain.md @@ -0,0 +1,71 @@ +# Get-FabricDomain + +## Overview + +The `Get-FabricDomain` function retrieves domain information from Microsoft Fabric. It provides flexible filtering options by domain ID, domain name, or non-empty domains. + +## Features + +- Supports filtering by `DomainId`, `DomainName`, or only returning domains containing workspaces (`NonEmptyDomainsOnly`). +- Ensures token validity before making API requests. +- Provides detailed logging of API requests, responses, and errors. + +## Parameters + +### `DomainId` *(Optional)* + +- **Description:** The unique identifier of the domain to retrieve. +- **Type:** String + +### `DomainName` *(Optional)* + +- **Description:** The display name of the domain to retrieve. +- **Type:** String + +### `NonEmptyDomainsOnly` *(Optional)* + +- **Description:** Filters the results to return only domains containing workspaces if set to `$true`. +- **Type:** Boolean +- **Default Value:** `$false` + +## Usage Examples + +### Example 1: Get a list of domains + +```powershell +Get-FabricDomain +``` + +### Example 2: Get a domain by Id + +```powershell +Get-FabricDomain -DomainId "2ef62c57-2e64-41fc-81c5-a80ad370172d" +``` + +### Example 3: Get a domain by Name + +```powershell +Get-FabricDomain -DomainName "API1" +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. **Input Validation:** Ensures only one of `DomainId` or `DomainName` is provided. +2. **Token Validation:** Calls `Test-TokenExpired` to ensure the token is valid. +3. **API URL Construction:** Dynamically builds the endpoint URL, including the `nonEmptyOnly` filter if required. +4. **API Request Execution:** Sends a GET request to the API endpoint. +5. **Response Handling:** + - Validates the response status code. + - Filters the results based on `DomainId` or `DomainName` if provided. +6. **Error Handling:** Catches and logs exceptions with detailed error messages. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricDomainWorkspace.md b/powershell/FabricACEToolkit/docs/Get-FabricDomainWorkspace.md new file mode 100644 index 0000000..d5ac9ec --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricDomainWorkspace.md @@ -0,0 +1,51 @@ +# Get-FabricDomainWorkspace + +## Overview + +The Get-FabricDomainWorkspace function retrieves the workspaces associated with a specific domain in Microsoft Fabric. It leverages the Fabric API to provide detailed information about workspaces for a given domain ID. + +## Features + +- Validates authentication token before making API requests. +- Constructs and calls the Fabric API endpoint to retrieve workspaces. +- Handles API response validation and logs errors effectively. + +## Parameters + +### DomainId *(Required)* + +- **Description:** The ID of the domain for which to retrieve workspaces. +- **Type:** String + +## Usage Examples + +### Example 1: Get a list workspaces associated to the domains + +```powershell +$domain = Get-FabricDomain -DomainName "API3" +Get-FabricDomainWorkspace -DomainId $domain.id +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the provided DomainId parameter. +2. Ensures the authentication token is valid. +3. Constructs the API endpoint URL based on the DomainId. +4. Retrieves workspace data via the Fabric API. +5. Handles and logs API responses, including empty or error cases. + +## Error Handling + +- Logs detailed error messages if API requests fail or invalid input is detected. +- Returns null for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEnvironment.md b/powershell/FabricACEToolkit/docs/Get-FabricEnvironment.md new file mode 100644 index 0000000..7c94762 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEnvironment.md @@ -0,0 +1,78 @@ +# Get-FabricEnvironment + +## Overview + +The `Get-FabricEnvironment` function sends a GET request to the Fabric API to retrieve environment details for a given workspace. It can filter the results by `EnvironmentName`. + +## Features + +- Retrieves environments from a specified workspace. +- Supports filtering environments by `EnvironmentId` or `EnvironmentName`. +- Handles pagination using continuation tokens. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Required)* + +- **Description:** The ID of the workspace to query environments. +- **Type:** String + +### EnvironmentId *(Optional)* + +- **Description:** The ID of a specific environment to retrieve. +- **Type:** String + +### EnvironmentName *(Optional)* + +- **Description:** The name of the specific environment to retrieve. +- **Type:** String + +## Usage Examples + +### Example 1: Get a list of environment list + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEnvironment -WorkspaceId $workspace.id +``` + +### Example 2: Get an environment by Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env01" +``` + +### Example 3: Get an environment by Id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentId "a94f2cfd-5fc2-46f5-9ef0-9ef5160af4bf" +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Handles ambiguous input by ensuring only one of `EnvironmentId` or `EnvironmentName` is provided. +2. Validates token validity before making API requests. +3. Constructs the API endpoint URL with or without a continuation token. +4. Sends the GET request to the Fabric API and processes the response. +5. Uses pagination (continuation tokens) to retrieve all environments in the workspace. +6. Filters the results based on the provided parameters (`EnvironmentId` or `EnvironmentName`). +7. Logs detailed information about API requests, responses, and errors. + +## Error Handling + +- Captures and logs any errors encountered during the API request. +- Handles API response codes and returns `null` if an error occurs. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentLibrary.md b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentLibrary.md new file mode 100644 index 0000000..12045eb --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentLibrary.md @@ -0,0 +1,57 @@ +# Get-FabricEnvironmentLibrary + +## Overview + +The `Get-FabricEnvironmentLibrary` function fetches library information for a given workspace and environment using the Microsoft Fabric API. It ensures the authentication token is valid and validates the response to handle errors gracefully. + +## Features + +- Retrieves the list of libraries associated with a specific environment in a Microsoft Fabric workspace. +- Validates the authentication token before making API requests. +- Handles API responses gracefully by validating status codes. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Required)* + +- **Description:** The unique identifier of the workspace where the environment is located. +- **Type:** String + +### EnvironmentId *(Required)* + +- **Description:** The unique identifier of the environment whose libraries are being queried. +- **Type:** String + +## Usage Examples + +### Example 1: Get a environment Library + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEnvironmentLibrary -WorkspaceId $workspace.id -EnvironmentId $env.id +``` + +## Prerequisites + +- The global `$FabricConfig` object must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API endpoint URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Sends a GET request to the Fabric API to retrieve the libraries. +4. Validates the API response and handles errors based on status codes. +5. Returns the retrieved libraries or `null` if an error occurs. + +## Error Handling + +- Captures and logs any errors encountered during the API request. +- Handles API response codes and returns `null` if an unexpected response occurs. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentSparkCompute.md b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentSparkCompute.md new file mode 100644 index 0000000..6ed484c --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentSparkCompute.md @@ -0,0 +1,58 @@ +# Get-FabricEnvironmentSparkCompute + +## Overview + +The `Get-FabricEnvironmentSparkCompute` function communicates with the Microsoft Fabric API to fetch information about Spark compute resources associated with a specified environment. It ensures that the API token is valid and gracefully handles errors during the API call. + +## Features + +- Retrieves the Spark compute details for a specific environment in a Microsoft Fabric workspace. +- Validates the authentication token before making API requests. +- Handles API responses gracefully by validating status codes. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Required)* + +- **Description:** The unique identifier of the workspace containing the target environment. +- **Type:** String + +### EnvironmentId *(Required)* + +- **Description:** The unique identifier of the environment whose Spark compute details are being retrieved. +- **Type:** String + +## Usage Examples + +### Example 1: Get Spark Compute for an enviroment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env01" +Get-FabricEnvironmentSparkCompute -WorkspaceId $workspace.id -EnvironmentId $env.id +``` + +## Prerequisites + +- The global `$FabricConfig` object must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API endpoint URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Sends a GET request to the Fabric API to retrieve Spark compute details. +4. Validates the API response and handles errors based on status codes. +5. Returns the retrieved Spark compute details or `null` if an error occurs. + +## Error Handling + +- Captures and logs any errors encountered during the API request. +- Handles API response codes and returns `null` if an unexpected response occurs. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingLibrary.md b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingLibrary.md new file mode 100644 index 0000000..4c6d143 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingLibrary.md @@ -0,0 +1,58 @@ +# Get-FabricEnvironmentStagingLibrary + +## Overview + +The `Get-FabricEnvironmentStagingLibrary` function interacts with the Microsoft Fabric API to fetch information about staging libraries associated with a specified environment. It ensures token validity and handles API errors gracefully. + +## Features + +- Retrieves the staging library details for a specific environment in a Microsoft Fabric workspace. +- Validates the authentication token before making API requests. +- Handles API responses gracefully by validating status codes. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Required)* + +- **Description:** The unique identifier of the workspace containing the target environment. +- **Type:** String + +### EnvironmentId *(Required)* + +- **Description:** The unique identifier of the environment for which staging library details are being retrieved. +- **Type:** String + +## Usage Examples + +### Example 1: Get all staging libraries associated with a specified environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env01" +Get-FabricEnvironmentStagingLibrary -WorkspaceId $workspace.id -EnvironmentId $env.id +``` + +## Prerequisites + +- The global `$FabricConfig` object must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API endpoint URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Sends a GET request to the Fabric API to retrieve staging library details. +4. Validates the API response and handles errors based on status codes. +5. Returns the retrieved staging library details or `null` if an error occurs. + +## Error Handling + +- Captures and logs any errors encountered during the API request. +- Handles API response codes and returns `null` if an unexpected response occurs. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingSparkCompute.md b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingSparkCompute.md new file mode 100644 index 0000000..19f066f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingSparkCompute.md @@ -0,0 +1,58 @@ +# Get-FabricEnvironmentStagingSparkCompute + +## Overview + +The `Get-FabricEnvironmentStagingSparkCompute` function interacts with the Microsoft Fabric API to fetch information about staging Spark compute configurations for a specified environment. It ensures token validity and handles API errors gracefully. + +## Features + +- Retrieves staging Spark compute details for a specific environment in a Microsoft Fabric workspace. +- Validates the authentication token before making API requests. +- Handles API responses gracefully by validating status codes. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Required)* + +- **Description:** The unique identifier of the workspace containing the target environment. +- **Type:** String + +### EnvironmentId *(Required)* + +- **Description:** The unique identifier of the environment for which staging Spark compute details are being retrieved. +- **Type:** String + +## Usage Examples + +### Example 1: Get staging Spark compute configurations for a specified environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env01" +Get-FabricEnvironmentStagingSparkCompute -WorkspaceId $workspace.id -EnvironmentId $env.id +``` + +## Prerequisites + +- The global `$FabricConfig` object must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API endpoint URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Sends a GET request to the Fabric API to retrieve staging Spark compute details. +4. Validates the API response and handles errors based on status codes. +5. Returns the retrieved staging Spark compute configurations or `null` if an error occurs. + +## Error Handling + +- Captures and logs any errors encountered during the API request. +- Handles API response codes and returns `null` if an unexpected response occurs. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEventhouse.md b/powershell/FabricACEToolkit/docs/Get-FabricEventhouse.md new file mode 100644 index 0000000..11ee163 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEventhouse.md @@ -0,0 +1,71 @@ +# Get-FabricEventhouse + +## Overview +The `Get-FabricEventhouse` function retrieves Eventhouse details from a specified Microsoft Fabric workspace using either the provided EventhouseId or EventhouseName. + +## Features +- Validates token expiration before making the API request. +- Supports retrieval by Eventhouse ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId +- **Description:** The unique identifier of the workspace where the Eventhouse exists. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseId +- **Description:** The unique identifier of the Eventhouse to retrieve. +- **Type:** String +- **Mandatory:** No + +### EventhouseName +- **Description:** The name of the Eventhouse to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Eventhouses + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEventhouse -WorkspaceId $workspace.id +``` + +### Example 2: Get a Eventhouses by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "eventhouse-12345" +``` + +### Example 2: Get a Eventhouses by id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEventhouse -WorkspaceId $workspace.id -EventhouseId "66ba709c-6531-4658-b189-68c7639b1ad8" +``` + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow +1. Ensures only one filter (`EventhouseId` or `EventhouseName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves Eventhouse details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEventhouseDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricEventhouseDefinition.md new file mode 100644 index 0000000..b2e8e1b --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEventhouseDefinition.md @@ -0,0 +1,68 @@ +# Get-FabricEventhouseDefinition + +## Overview + +The `Get-FabricEventhouseDefinition` function retrieves the definition of an Eventhouse from a specified Microsoft Fabric workspace using the provided Eventhouse ID. It supports token validation, API URL construction, and response handling. + +## Features + +- Validates token expiration before making the API request. +- Constructs and sends an API request to retrieve the Eventhouse definition. +- Handles long-running operations for retrieving the definition. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventhouse exists. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseId + +- **Description:** The unique identifier of the Eventhouse to retrieve the definition for. +- **Type:** String +- **Mandatory:** Optional + +### EventhouseFormat + +- **Description:** The format in which to retrieve the Eventhouse definition. +- **Type:** String +- **Mandatory:** Optional + +## Usage Examples + +### Example 1: Retrieve an Eventhouse Definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$eventhouse = Get-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "eventhouse-67890" +Get-FabricEventhouseDefinition -WorkspaceId $workspace.id -EventhouseId $eventhouse.id +``` + +This example retrieves the definition of the Eventhouse with ID `eventhouse-67890` in the workspace with ID `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, `EventhouseId`, and `EventhouseFormat` (if provided). +3. Sends a POST request to retrieve the Eventhouse definition. +4. Handles both immediate responses and long-running operations. +5. Validates the API response and processes the definition. + +## Error Handling + +- Logs descriptive error messages for failed API requests or invalid inputs. +- Returns `null` for any errors encountered during execution. +- Handles long-running operations and retries if necessary. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEventstream.md b/powershell/FabricACEToolkit/docs/Get-FabricEventstream.md new file mode 100644 index 0000000..27873c6 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEventstream.md @@ -0,0 +1,71 @@ +# Get-FabricEventstream + +## Overview +The `Get-FabricEventstream` function retrieves Eventstream details from a specified Microsoft Fabric workspace using either the provided EventstreamId or EventstreamName. + +## Features +- Validates token expiration before making the API request. +- Supports retrieval by Eventstream ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId +- **Description:** The unique identifier of the workspace where the Eventstream exists. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamId +- **Description:** The unique identifier of the Eventstream to retrieve. +- **Type:** String +- **Mandatory:** No + +### EventstreamName +- **Description:** The name of the Eventstream to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Eventstreams + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEventstream -WorkspaceId $workspace.id +``` + +### Example 2: Get a Eventstreams by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEventstream -WorkspaceId $workspace.id -EventstreamName "Eventstream-12345" +``` + +### Example 2: Get a Eventstreams by id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricEventstream -WorkspaceId $workspace.id -EventstreamId "66ba709c-6531-4658-b189-68c7639b1ad8" +``` + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow +1. Ensures only one filter (`EventstreamId` or `EventstreamName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves Eventstream details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricEventstreamDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricEventstreamDefinition.md new file mode 100644 index 0000000..1008661 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricEventstreamDefinition.md @@ -0,0 +1,68 @@ +# Get-FabricEventstreamDefinition + +## Overview + +The `Get-FabricEventstreamDefinition` function retrieves the definition of an Eventstream from a specified Microsoft Fabric workspace using the provided Eventstream ID. It supports token validation, API URL construction, and response handling. + +## Features + +- Validates token expiration before making the API request. +- Constructs and sends an API request to retrieve the Eventstream definition. +- Handles long-running operations for retrieving the definition. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventstream exists. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamId + +- **Description:** The unique identifier of the Eventstream to retrieve the definition for. +- **Type:** String +- **Mandatory:** Optional + +### EventstreamFormat + +- **Description:** The format in which to retrieve the Eventstream definition. +- **Type:** String +- **Mandatory:** Optional + +## Usage Examples + +### Example 1: Retrieve an Eventstream Definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$Eventstream = Get-FabricEventstream -WorkspaceId $workspace.id -EventstreamName "Eventstream-67890" +Get-FabricEventstreamDefinition -WorkspaceId $workspace.id -EventstreamId $Eventstream.id +``` + +This example retrieves the definition of the Eventstream with ID `Eventstream-67890` in the workspace with ID `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, `EventstreamId`, and `EventstreamFormat` (if provided). +3. Sends a POST request to retrieve the Eventstream definition. +4. Handles both immediate responses and long-running operations. +5. Validates the API response and processes the definition. + +## Error Handling + +- Logs descriptive error messages for failed API requests or invalid inputs. +- Returns `null` for any errors encountered during execution. +- Handles long-running operations and retries if necessary. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboard.md b/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboard.md new file mode 100644 index 0000000..f839087 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboard.md @@ -0,0 +1,79 @@ +# Get-FabricKQLDashboard + +## Overview + +The `Get-FabricKQLDashboard` function retrieves KQLDashboard details from a specified Microsoft Fabric workspace using either the provided KQLDashboardId or KQLDashboardName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by KQLDashboard ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the KQLDashboard exists. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardId + +- **Description:** The unique identifier of the KQLDashboard to retrieve. +- **Type:** String +- **Mandatory:** No + +### KQLDashboardName + +- **Description:** The name of the KQLDashboard to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of KQLDashboards + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKQLDashboard -WorkspaceId $workspace.id +``` + +### Example 2: Get a KQLDashboards by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKQLDashboard -WorkspaceId $workspace.id -KQLDashboardName "KQLDashboard-12345" +``` + +### Example 2: Get a KQLDashboards by id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKQLDashboard -WorkspaceId $workspace.id -KQLDashboardId "66ba709c-6531-4658-b189-68c7639b1ad8" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`KQLDashboardId` or `KQLDashboardName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves KQLDashboard details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboardDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboardDefinition.md new file mode 100644 index 0000000..cb748af --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboardDefinition.md @@ -0,0 +1,68 @@ +# Get-FabricKQLDashboardDefinition + +## Overview + +Retrieves the definition of a KQLDashboard from a specific workspace in Microsoft Fabric. This function supports synchronous and asynchronous operations and includes detailed logging and error handling. + +## Features + +- Fetches KQLDashboard content or metadata. +- Supports optional parameters for KQLDashboard ID and format. +- Handles long-running operations asynchronously. +- Validates token expiration before making API requests. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the KQLDashboard definition is to be retrieved. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardId + +- **Description:** The unique identifier of the KQLDashboard whose definition needs to be retrieved. +- **Type:** String +- **Mandatory:** No + +### KQLDashboardFormat + +- **Description:** Specifies the format of the KQLDashboard definition. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get KQL Dashboard definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$kqlDashboard = Get-FabricKqlDashboard -WorkspaceId $workspace.id -KqlDashboardName "KQLDashboard-12345" +Get-FabricKqlDashboardDefinition -WorkspaceId $workspace.id -KqlDashboardId $kqlDashboard.id +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and optionally `KQLDashboardId` and `KQLDashboardFormat`. +3. Sends a POST request to fetch the KQLDashboard definition. +4. Handles API responses: + - `200`: Returns the dashboard definition. + - `202`: Manages long-running operations to fetch the definition asynchronously. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs errors for invalid input or failed API requests. +- Returns detailed error messages to assist with troubleshooting. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabase.md b/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabase.md new file mode 100644 index 0000000..a14727b --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabase.md @@ -0,0 +1,85 @@ +# Get-FabricKQLDatabase + +## Overview + +Retrieves a KQLDatabase or a list of KQLDatabases from a specified Microsoft Fabric workspace by sending a GET request to the Microsoft Fabric API. This function supports filtering results by `KQLDatabaseName` or `KQLDatabaseId`. + +## Features + +- Fetches details of all KQLDatabases in a specified workspace. +- Supports filtering by `KQLDatabaseName` or `KQLDatabaseId`. +- Handles pagination using continuation tokens for retrieving large datasets. +- Ensures robust token validation and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace to query KQLDatabases. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseId + +- **Description:** The unique identifier of the specific KQLDatabase to retrieve. +- **Type:** String +- **Mandatory:** No + +### KQLDatabaseName + +- **Description:** The name of the KQLDatabase to retrieve. +- **Type:** String +- **Mandatory:** No +- **Validation:** Must contain only alphanumeric characters, underscores, or spaces. + +## Usage Examples + +### Example 1: Get a list of KQL Database list + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKqlDatabase -WorkspaceId $workspace.id +``` + +### Example 2: Get a KQL Database by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseName "KQLDB-12345" +``` + +### Example 3: Get a KQL Database by id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseId "63caa83a-e8e7-414c-9272-2091156da26b" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates input parameters to ensure only one of `KQLDatabaseId` or `KQLDatabaseName` is provided. +2. Ensures the authentication token is valid using `Test-TokenExpired`. +3. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and optional `continuationToken`. +4. Sends a GET request to the Microsoft Fabric API. +5. Handles API responses: + - Adds data from the response to the result set. + - Continues fetching data if a continuation token is provided. +6. Filters the results based on the provided `KQLDatabaseId` or `KQLDatabaseName`. +7. Returns the matched KQLDatabase(s) or logs a warning if no match is found. + +## Error Handling + +- Validates the input parameters to avoid ambiguous queries. +- Logs detailed error messages for invalid responses or API failures. +- Captures and logs exceptions during API calls for debugging. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabaseDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabaseDefinition.md new file mode 100644 index 0000000..d31c369 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabaseDefinition.md @@ -0,0 +1,72 @@ +# Get-FabricKQLDatabaseDefinition + +## Overview + +Retrieves the definition of a KQLDatabase from a specified Microsoft Fabric workspace. This function supports fetching KQLDatabase definitions in the KQLDatabase format and handles long-running asynchronous operations when necessary. + +## Features + +- Fetches the content or metadata of a specific KQLDatabase in a workspace. +- Handles long-running operations with detailed logging. +- Includes robust error handling and token validation. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the KQLDatabase definition is to be retrieved. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseId + +- **Description:** The unique identifier of the KQLDatabase whose definition needs to be retrieved. +- **Type:** String +- **Mandatory:** No + +### KQLDatabaseFormat + +- **Description:** Specifies the format of the KQLDatabase definition. Currently, only 'ipynb' is supported. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a KQL database definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$kqlDatabase = Get-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseName "KQLDB-12345" +Update-FabricKqlDatabaseDefinition ` +-WorkspaceId $workspace.id ` +-KqlDatabaseId $kqlDatabase.id ` +-KqlDatabasePathDefinition "C:\temp\API\KQLDatabase\KQLDatabase-definition.json" ` +-KQLDatabasePathSchemaDefinition "C:\temp\API\KQLDatabase\DatabaseSchema.kql"` +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Microsoft Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. +- Long-running operations are handled by `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult`. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and optionally `KQLDatabaseId`. +3. Sends a POST request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: Retrieves and returns the KQLDatabase definition. + - `202`: Handles asynchronous operation and fetches the definition upon completion. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Supports debugging with detailed information about long-running operations, including `OperationId`, `Location`, and `Retry-After` values. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricKQLQueryset.md b/powershell/FabricACEToolkit/docs/Get-FabricKQLQueryset.md new file mode 100644 index 0000000..8c0d4e4 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricKQLQueryset.md @@ -0,0 +1,85 @@ +# Get-FabricKQLQueryset + +## Overview + +Retrieves a KQLQueryset or a list of KQLQuerysets from a specified Microsoft Fabric workspace by sending a GET request to the Microsoft Fabric API. This function supports filtering results by `KQLQuerysetName` or `KQLQuerysetId`. + +## Features + +- Fetches details of all KQLQuerysets in a specified workspace. +- Supports filtering by `KQLQuerysetName` or `KQLQuerysetId`. +- Handles pagination using continuation tokens for retrieving large datasets. +- Ensures robust token validation and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace to query KQLQuerysets. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetId + +- **Description:** The unique identifier of the specific KQLQueryset to retrieve. +- **Type:** String +- **Mandatory:** No + +### KQLQuerysetName + +- **Description:** The name of the KQLQueryset to retrieve. +- **Type:** String +- **Mandatory:** No +- **Validation:** Must contain only alphanumeric characters, underscores, or spaces. + +## Usage Examples + +### Example 1: Get a list of KQL Database list + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKQLQueryset -WorkspaceId $workspace.id +``` + +### Example 2: Get a KQL Database by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetName "KQLDB-12345" +``` + +### Example 3: Get a KQL Database by id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetId "63caa83a-e8e7-414c-9272-2091156da26b" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates input parameters to ensure only one of `KQLQuerysetId` or `KQLQuerysetName` is provided. +2. Ensures the authentication token is valid using `Test-TokenExpired`. +3. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and optional `continuationToken`. +4. Sends a GET request to the Microsoft Fabric API. +5. Handles API responses: + - Adds data from the response to the result set. + - Continues fetching data if a continuation token is provided. +6. Filters the results based on the provided `KQLQuerysetId` or `KQLQuerysetName`. +7. Returns the matched KQLQueryset(s) or logs a warning if no match is found. + +## Error Handling + +- Validates the input parameters to avoid ambiguous queries. +- Logs detailed error messages for invalid responses or API failures. +- Captures and logs exceptions during API calls for debugging. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricKQLQuerysetDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricKQLQuerysetDefinition.md new file mode 100644 index 0000000..f6f98fd --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricKQLQuerysetDefinition.md @@ -0,0 +1,72 @@ +# Get-FabricKQLQuerysetDefinition + +## Overview + +Retrieves the definition of a KQLQueryset from a specified Microsoft Fabric workspace. This function supports fetching KQLQueryset definitions in the KQLQueryset format and handles long-running asynchronous operations when necessary. + +## Features + +- Fetches the content or metadata of a specific KQLQueryset in a workspace. +- Handles long-running operations with detailed logging. +- Includes robust error handling and token validation. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the KQLQueryset definition is to be retrieved. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetId + +- **Description:** The unique identifier of the KQLQueryset whose definition needs to be retrieved. +- **Type:** String +- **Mandatory:** No + +### KQLQuerysetFormat + +- **Description:** Specifies the format of the KQLQueryset definition. Currently, only 'ipynb' is supported. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a KQL Queryset definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$KQLQueryset = Get-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetName "KQLDB-12345" +Update-FabricKQLQuerysetDefinition ` +-WorkspaceId $workspace.id ` +-KQLQuerysetId $KQLQueryset.id ` +-KQLQuerysetPathDefinition "C:\temp\API\KQLQueryset\KQLQueryset-definition.json" ` +-KQLQuerysetPathSchemaDefinition "C:\temp\API\KQLQueryset\DatabaseSchema.kql"` +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Microsoft Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. +- Long-running operations are handled by `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult`. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and optionally `KQLQuerysetId`. +3. Sends a POST request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: Retrieves and returns the KQLQueryset definition. + - `202`: Handles asynchronous operation and fetches the definition upon completion. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Supports debugging with detailed information about long-running operations, including `OperationId`, `Location`, and `Retry-After` values. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricLakehouse.md b/powershell/FabricACEToolkit/docs/Get-FabricLakehouse.md new file mode 100644 index 0000000..4b1364d --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricLakehouse.md @@ -0,0 +1,76 @@ +# Get-FabricLakehouse + +## Overview + +Retrieves a Lakehouse or a list of Lakehouses from a specified workspace in Microsoft Fabric. + +## Description + +The `Get-FabricLakehouse` function sends a GET request to the Fabric API to retrieve Lakehouse details for a given workspace. It can filter the results by `LakehouseName`. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace to query Lakehouses. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseName + +- **Description:** (Optional) The name of the specific Lakehouse to retrieve. +- **Type:** String +- **Mandatory:** No + +### LakehouseId + +- **Description:** (Optional) The ID of the specific Lakehouse to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Lakehouse +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricLakehouse -WorkspaceId $workspace.id +``` + +### Example 2: Get Lakehouse by Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "LH01" +``` + +### Example 3: Get Lakehouse by Id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseId "8f64ee06-62c8-45c8-83ec-ea1a30f0fe89" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Sends a GET request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: Lakehouse(s) retrieved successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricLakehouseTable.md b/powershell/FabricACEToolkit/docs/Get-FabricLakehouseTable.md new file mode 100644 index 0000000..7c30c41 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricLakehouseTable.md @@ -0,0 +1,67 @@ +# Get-FabricLakehouseTable + +## Overview + +Retrieves tables from a specific Lakehouse in Microsoft Fabric. + +## Description + +The `Get-FabricLakehouseTable` function sends a GET request to the Fabric API to retrieve table details for a specified Lakehouse within a workspace. It handles pagination using continuation tokens to retrieve all available tables. + +## Features + +- Ensures token validity before making API requests. +- Constructs the API URL dynamically based on provided parameters. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace where the Lakehouse resides. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseId + +- **Description:** The ID of the Lakehouse from which to retrieve tables. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Retrieve tables from a specific Lakehouse + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "lakehouse-12345" +Get-FabricLakehouseTable -WorkspaceId $workspace.id -LakehouseId $lakehouse.id +``` + +Retrieves all tables from Lakehouse with ID "67890" in workspace "12345". + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `LakehouseId`. +3. Sends a GET request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: Tables retrieved successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for API failures or invalid inputs. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperation.md b/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperation.md new file mode 100644 index 0000000..4d05964 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperation.md @@ -0,0 +1,74 @@ +# Get-FabricLongRunningOperation + +## Overview + +The `Get-FabricLongRunningOperation` function monitors the status of a long-running operation in Microsoft Fabric by periodically polling the operation status until it reaches a terminal state (Succeeded or Failed). + +## Features + +- Supports monitoring using an operation ID or a location header. +- Allows customizable polling intervals. +- Provides descriptive error handling and logging. + +## Parameters + +### operationId + +- **Description:** The unique identifier of the long-running operation to be monitored. +- **Type:** String +- **Mandatory:** No + +### location + +- **Description:** The location header URL for the long-running operation. +- **Type:** String +- **Mandatory:** No + +### retryAfter + +- **Description:** The interval (in seconds) to wait between polling requests. Defaults to 5 seconds. +- **Type:** Integer +- **Mandatory:** No + +## Usage Examples + +### Example 1: Monitor an operation by ID + +```powershell +Get-FabricLongRunningOperation -operationId "12345-abcd-67890-efgh" -retryAfter 10 + +# Polls the status of the operation every 10 seconds until it completes. +``` + +### Example 2: Monitor an operation using the location header + +```powershell +Get-FabricLongRunningOperation -location "https://api.fabric.microsoft.com/v1/operations/12345-abcd" + +# Uses the location header URL to monitor the operation. +``` + +## Prerequisites + +- Use the `$FabricConfig` global object, which must include: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Ensure valid authentication headers are set. + +## Key Workflow + +1. Constructs the API URL based on `operationId` or `location`. +2. Waits for the specified interval (`retryAfter`) before polling. +3. Sends a GET request to retrieve the operation status. +4. Continues polling until the operation reaches a terminal state. +5. Logs descriptive messages for debugging and error handling. +6. Returns the operation result. + +## Error Handling + +- Logs detailed error messages if API requests fail. +- Throws exceptions for invalid input or HTTP errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperationResult.md b/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperationResult.md new file mode 100644 index 0000000..466039c --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperationResult.md @@ -0,0 +1,52 @@ +# Get-FabricLongRunningOperationResult + +## Overview + +The `Get-FabricLongRunningOperationResult` function retrieves the result of a completed long-running operation from the Microsoft Fabric API. This function is typically used after confirming that the operation has successfully completed. + +## Features + +- Fetches the result of a completed long-running operation. +- Validates the response and provides detailed logging. +- Ensures error handling for API requests. + +## Parameters + +### operationId + +- **Description:** The unique identifier of the completed long-running operation whose result you want to retrieve. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Retrieve the result of a completed operation + +```powershell +Get-FabricLongRunningOperationResult -operationId "12345-abcd-67890-efgh" + +# Fetches the result of the specified operation ID. +``` + +## Prerequisites + +- Use the `$FabricConfig` global object, which must include: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Ensure the operation has completed before calling this function. + +## Key Workflow + +1. Constructs the API URL based on the `operationId`. +2. Sends a GET request to fetch the operation result. +3. Validates the response and logs messages for debugging. +4. Returns the operation result or logs errors if any issues occur. + +## Error Handling + +- Logs detailed error messages if API requests fail. +- Throws exceptions for invalid input or HTTP errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricMLExperiment.md b/powershell/FabricACEToolkit/docs/Get-FabricMLExperiment.md new file mode 100644 index 0000000..a17de81 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricMLExperiment.md @@ -0,0 +1,80 @@ +# Get-FabricMLExperiment + +## Overview +The `Get-FabricMLExperiment` function retrieves ML Experiment details from a specified Microsoft Fabric workspace using either the provided MLExperimentId or MLExperimentName. + +## Features +- Validates token expiration before making the API request. +- Supports retrieval by ML Experiment ID or name. +- Handles paginated API responses using continuation tokens. +- Provides detailed error handling and logging for debugging. + +## Parameters + +### WorkspaceId +- **Description:** The unique identifier of the workspace where the ML Experiment exists. +- **Type:** String +- **Mandatory:** Yes + +### MLExperimentId +- **Description:** The unique identifier of the ML Experiment to retrieve. +- **Type:** String +- **Mandatory:** No + +### MLExperimentName +- **Description:** The name of the ML Experiment to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve an ML Experiment by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMLExperiment -WorkspaceId $workspace.id -MLExperimentId "MLexperiment-67890" +``` + +This example retrieves the ML Experiment details for the experiment with ID `MLexperiment-67890` in the workspace with ID `workspace-12345`. + +### Example 2: Retrieve an ML Experiment by Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMLExperiment -WorkspaceId $workspace.id -MLExperimentName "MLexperiment-12345" +``` + +This example retrieves the ML Experiment details for the experiment named `MLexperiment-12345` in the workspace with ID `workspace-12345`. + +### Example 3: Retrieve All ML Experiments in a Workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMLExperiment -WorkspaceId $workspace.id +``` + +This example retrieves all ML Experiments in the workspace with ID `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`MLExperimentId` or `MLExperimentName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves ML Experiment details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs detailed error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricMLModel.md b/powershell/FabricACEToolkit/docs/Get-FabricMLModel.md new file mode 100644 index 0000000..3533af9 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricMLModel.md @@ -0,0 +1,80 @@ +# Get-FabricMLModel + +## Overview +The `Get-FabricMLModel` function retrieves ML Model details from a specified Microsoft Fabric workspace using either the provided MLModelId or MLModelName. + +## Features +- Validates token expiration before making the API request. +- Supports retrieval by ML Model ID or name. +- Handles paginated API responses using continuation tokens. +- Provides detailed error handling and logging for debugging. + +## Parameters + +### WorkspaceId +- **Description:** The unique identifier of the workspace where the ML Model exists. +- **Type:** String +- **Mandatory:** Yes + +### MLModelId +- **Description:** The unique identifier of the ML Model to retrieve. +- **Type:** String +- **Mandatory:** No + +### MLModelName +- **Description:** The name of the ML Model to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve an ML Model by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMLModel -WorkspaceId $workspace.id -MLModelId "MLModel-67890" +``` + +This example retrieves the ML Model details for the experiment with ID `MLModel-67890` in the workspace with ID `workspace-12345`. + +### Example 2: Retrieve an ML Model by Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMLModel -WorkspaceId $workspace.id -MLModelName "MLModel-12345" +``` + +This example retrieves the ML Model details for the experiment named `MLModel-12345` in the workspace with ID `workspace-12345`. + +### Example 3: Retrieve All ML Models in a Workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMLModel -WorkspaceId $workspace.id +``` + +This example retrieves all ML Models in the workspace with ID `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`MLModelId` or `MLModelName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves ML Model details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs detailed error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabase.md b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabase.md new file mode 100644 index 0000000..031faba --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabase.md @@ -0,0 +1,79 @@ +# Get-FabricMirroredDatabase + +## Overview + +The `Get-FabricMirroredDatabase` function retrieves MirroredDatabase details from a specified Microsoft Fabric workspace. It supports filtering by either `MirroredDatabaseId` or `MirroredDatabaseName`. + +## Features + +- Validates token expiration before making the API request. +- Handles ambiguous input by ensuring only one filter parameter is specified. +- Supports paginated API responses using continuation tokens. +- Provides detailed error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace to query MirroredDatabases. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabaseId + +- **Description:** The unique identifier of the MirroredDatabase to retrieve. +- **Type:** String +- **Mandatory:** No + +### MirroredDatabaseName + +- **Description:** The name of the MirroredDatabase to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve all MirroredDatabases in a workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMirroredDatabase -WorkspaceId $workspace.id +``` + +### Example 2: Retrieve a specific MirroredDatabase by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMirroredDatabase -WorkspaceId $workspace.id -Debug -MirroredDatabaseName "WideWorldImportersDW" +``` + +### Example 2: Retrieve a specific MirroredDatabase by id + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMirroredDatabase -WorkspaceId $workspace.id -Debug -MirroredDatabaseId "7c3d98fb-8b60-4924-8e15-24212a7a8356" +``` + +## Prerequisites + +- Use the global configuration variable `$FabricConfig`, which must include: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`MirroredDatabaseId` or `MirroredDatabaseName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves MirroredDatabase details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseDefinition.md new file mode 100644 index 0000000..689f7ed --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseDefinition.md @@ -0,0 +1,62 @@ +# Get-FabricMirroredDatabaseDefinition + +## Overview + +The `Get-FabricMirroredDatabaseDefinition` function retrieves the definition of a MirroredDatabase from a specific workspace in Microsoft Fabric. The function supports synchronous and asynchronous operations, ensuring detailed logging and error handling throughout the process. + +## Features + +- Validates token expiration before making the API request. +- Retrieves MirroredDatabase definitions either for a specific database or all databases in a workspace. +- Handles long-running operations asynchronously. +- Provides detailed logging and error handling for seamless operation. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace to query for MirroredDatabase definitions. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabaseId + +- **Description:** The unique identifier of the MirroredDatabase to retrieve the definition for. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get the definition of a specific MirroredDatabase + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDW" +Get-FabricMirroredDatabaseDefinition -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. +- Long-running operations are managed using the `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult` helper functions. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL for retrieving MirroredDatabase definitions. +3. Handles API responses, including synchronous (200 OK) and asynchronous (202 Accepted) operations. +4. Manages long-running operations and retrieves the result upon successful completion. +5. Provides descriptive logging for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Handles unexpected API response codes and logs detailed error information. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseStatus.md b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseStatus.md new file mode 100644 index 0000000..787ba15 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseStatus.md @@ -0,0 +1,60 @@ +# Get-FabricMirroredDatabaseStatus + +## Overview + +The `Get-FabricMirroredDatabaseStatus` function retrieves the mirroring status of a MirroredDatabase from a specified Microsoft Fabric workspace. It supports retrieving the status of all databases in the workspace or a specific database using its unique identifier. + +## Features + +- Validates token expiration before making the API request. +- Constructs the API URL dynamically based on provided parameters. +- Handles API responses and logs detailed information for debugging. +- Provides error handling with descriptive messages for operational clarity. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace containing the MirroredDatabase. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabaseId + +- **Description:** The unique identifier of the MirroredDatabase for which to retrieve the status. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve the status of a specific MirroredDatabase + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDW" +Get-FabricMirroredDatabaseStatus -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id +``` + +## Prerequisites + +- Use the global configuration variable `$FabricConfig`, which must include: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using the `WorkspaceId` and optionally the `MirroredDatabaseId`. +3. Sends an API request to retrieve the mirroring status. +4. Processes the API response, ensuring valid status codes and handling errors. +5. Logs detailed messages for debugging and operational clarity. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseTableStatus.md b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseTableStatus.md new file mode 100644 index 0000000..87414cb --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseTableStatus.md @@ -0,0 +1,62 @@ +# Get-FabricMirroredDatabaseTableStatus + +## Overview + +The `Get-FabricMirroredDatabaseTableStatus` function retrieves the mirroring status of all tables in a MirroredDatabase within a specified Microsoft Fabric workspace. It supports handling paginated API responses using continuation tokens for large datasets. + +## Features + +- Validates token expiration before making the API request. +- Dynamically constructs API URLs with optional continuation tokens for paginated responses. +- Retrieves data iteratively, adding all results to a consolidated list. +- Provides detailed logging for debugging and monitoring purposes. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace containing the MirroredDatabase. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabaseId + +- **Description:** The unique identifier of the MirroredDatabase for which to retrieve table statuses. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve all table statuses for a specific MirroredDatabase + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDW" +Get-FabricMirroredDatabaseTableStatus -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id +``` + +## Prerequisites + +- Use the global configuration variable `$FabricConfig`, which must include: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. +- The `System.Web` assembly is loaded dynamically if not already available. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the base API URL using `WorkspaceId` and optionally `MirroredDatabaseId`. +3. Iterates through paginated responses using continuation tokens, consolidating results. +4. Logs detailed messages for debugging and operational clarity. +5. Returns a list of table mirroring statuses for the specified MirroredDatabase or all tables in the workspace. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. +- Captures and logs error details, including API response codes and continuation token updates. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricMirroredWarehouse.md b/powershell/FabricACEToolkit/docs/Get-FabricMirroredWarehouse.md new file mode 100644 index 0000000..cb3c97c --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricMirroredWarehouse.md @@ -0,0 +1,63 @@ +# Get-FabricMirroredWarehouse + +## Overview + +Retrieves a MirroredWarehouse or a list of MirroredWarehouses from a specified workspace in Microsoft Fabric. + +## Description + +The `Get-FabricMirroredWarehouse` function sends a GET request to the Fabric API to retrieve MirroredWarehouse details for a given workspace. It can filter the results by `MirroredWarehouseName`. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace to query MirroredWarehouses. +- **Type:** String +- **Mandatory:** Yes + +### MirroredWarehouseName + +- **Description:** (Optional) The name of the specific MirroredWarehouse to retrieve. +- **Type:** String +- **Mandatory:** No + +### MirroredWarehouseId + +- **Description:** (Optional) The ID of the specific MirroredWarehouse to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve a MirroredWarehouse by Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricMirroredWarehouse -WorkspaceId $workspace.id +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Sends a GET request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: MirroredWarehouse(s) retrieved successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricNotebook.md b/powershell/FabricACEToolkit/docs/Get-FabricNotebook.md new file mode 100644 index 0000000..42fe929 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricNotebook.md @@ -0,0 +1,79 @@ +# Get-FabricNotebook + +## Overview + +The `Get-FabricNotebook` function retrieves Notebook details from a specified Microsoft Fabric workspace using either the provided NotebookId or NotebookName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by Notebook ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Notebook exists. +- **Type:** String +- **Mandatory:** Yes + +### NotebookId + +- **Description:** The unique identifier of the Notebook to retrieve. +- **Type:** String +- **Mandatory:** No + +### NotebookName + +- **Description:** The name of the Notebook to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Notebooks + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricNotebook -WorkspaceId $workspace.id +``` + +### Example 2: Get a Notebook by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Development" +``` + +### Example 3: Get a Notebook by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricNotebook -WorkspaceId $workspace.id -NotebookId "12345-67890" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`NotebookId` or `NotebookName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves Notebook details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricNotebookDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricNotebookDefinition.md new file mode 100644 index 0000000..156a456 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricNotebookDefinition.md @@ -0,0 +1,58 @@ +# Get-FabricNotebookDefinition + +## Overview + +The `Get-FabricNotebookDefinition` function retrieves the definition of a notebook from a specific workspace in Microsoft Fabric. + +## Description + +This function fetches the notebook's content or metadata from a workspace. It supports retrieving notebook definitions in the Jupyter Notebook (`ipynb`) format. Handles both synchronous and asynchronous operations, with detailed logging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the notebook definition is to be retrieved. +- **Type:** String +- **Mandatory:** Yes + +### NotebookId + +- **Description:** (Optional) The unique identifier of the notebook whose definition needs to be retrieved. +- **Type:** String +- **Mandatory:** No + +### NotebookFormat + +- **Description:** Specifies the format of the notebook definition. Currently, only 'ipynb' is supported. +- **Type:** String +- **Mandatory:** No +- **Default:** 'ipynb' + +## Examples + +### Example 1: Retrieve a Notebook Definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$notebook = Get-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Notebook03" +Get-FabricNotebookDefinition -WorkspaceId $workspace.id -NotebookId $notebook.id +``` + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, `NotebookId`, and `NotebookFormat` (if provided). +3. Sends a POST request to retrieve the Notebook definition. +4. Handles both immediate responses and long-running operations. +5. Validates the API response and processes the definition. + +## Error Handling + +- Logs descriptive error messages for failed API requests or invalid inputs. +- Returns `null` for any errors encountered during execution. +- Handles long-running operations and retries if necessary. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricPaginatedReport.md b/powershell/FabricACEToolkit/docs/Get-FabricPaginatedReport.md new file mode 100644 index 0000000..1d5dbf8 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricPaginatedReport.md @@ -0,0 +1,79 @@ +# Get-FabricPaginatedReport + +## Overview + +The `Get-FabricPaginatedReport` function retrieves paginated report details from a specified Microsoft Fabric workspace using either the provided PaginatedReportId or PaginatedReportName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by paginated report ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the paginated reports exist. +- **Type:** String +- **Mandatory:** Yes + +### PaginatedReportId + +- **Description:** The unique identifier of the paginated report to retrieve. +- **Type:** String +- **Mandatory:** No + +### PaginatedReportName + +- **Description:** The name of the paginated report to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of paginated reports + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricPaginatedReport -WorkspaceId $workspace.id +``` + +### Example 2: Get a paginated report by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricPaginatedReport -WorkspaceId $workspace.id -PaginatedReportName "My Paginated Report" +``` + +### Example 3: Get a paginated report by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricPaginatedReport -WorkspaceId $workspace.id -PaginatedReportId "report-67890" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`PaginatedReportId` or `PaginatedReportName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves paginated report details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricReflex.md b/powershell/FabricACEToolkit/docs/Get-FabricReflex.md new file mode 100644 index 0000000..695e707 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricReflex.md @@ -0,0 +1,79 @@ +# Get-FabricReflex + +## Overview + +The `Get-FabricReflex` function retrieves Reflex details from a specified Microsoft Fabric workspace using either the provided ReflexId or ReflexName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by Reflex ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Reflex exists. +- **Type:** String +- **Mandatory:** Yes + +### ReflexId + +- **Description:** The unique identifier of the Reflex to retrieve. +- **Type:** String +- **Mandatory:** No + +### ReflexName + +- **Description:** The name of the Reflex to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Reflexes + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricReflex -WorkspaceId $workspace.id +``` + +### Example 2: Get a Reflex by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricReflex -WorkspaceId $workspace.id -ReflexName "My Reflex" +``` + +### Example 3: Get a Reflex by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricReflex -WorkspaceId $workspace.id -ReflexId "Reflex-67890" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`ReflexId` or `ReflexName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves Reflex details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricReflexDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricReflexDefinition.md new file mode 100644 index 0000000..dbfa867 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricReflexDefinition.md @@ -0,0 +1,68 @@ +# Get-FabricReflexDefinition + +## Overview + +Retrieves the definition of a Reflex from a specified Microsoft Fabric workspace. This function supports fetching Reflex definitions in various formats and handles long-running asynchronous operations when necessary. + +## Features + +- Fetches the content or metadata of a specific Reflex in a workspace. +- Handles long-running operations with detailed logging. +- Includes robust error handling and token validation. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Reflex exists. +- **Type:** String +- **Mandatory:** Yes + +### ReflexId + +- **Description:** The unique identifier of the Reflex whose definition needs to be retrieved. +- **Type:** String +- **Mandatory:** No + +### ReflexFormat + +- **Description:** Specifies the format of the Reflex definition to retrieve. This parameter is optional. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve a Reflex definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$reflex = Get-FabricReflex -WorkspaceId $workspace.id -ReflexName "Reflex01" +Get-FabricReflexDefinition -WorkspaceId $workspace.id -ReflexId $reflex.id +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Microsoft Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. +- Long-running operations are handled by `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult`. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and optionally `ReflexId`. +3. Sends a POST request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: Retrieves and returns the Reflex definition. + - `202`: Handles asynchronous operation and fetches the definition upon completion. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Supports debugging with detailed information about long-running operations, including `OperationId`, `Location`, and `Retry-After` values. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricReport.md b/powershell/FabricACEToolkit/docs/Get-FabricReport.md new file mode 100644 index 0000000..6347951 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricReport.md @@ -0,0 +1,79 @@ +# Get-FabricReport + +## Overview + +The `Get-FabricReport` function retrieves Report details from a specified Microsoft Fabric workspace using either the provided ReportId or ReportName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by Report ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Report exists. +- **Type:** String +- **Mandatory:** Yes + +### ReportId + +- **Description:** The unique identifier of the Report to retrieve. +- **Type:** String +- **Mandatory:** No + +### ReportName + +- **Description:** The name of the Report to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Reports + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricReport -WorkspaceId $workspace.id +``` + +### Example 2: Get a Report by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricReport -WorkspaceId $workspace.id -ReportName "My Report" +``` + +### Example 3: Get a Report by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricReport -WorkspaceId $workspace.id -ReportId "12345-67890" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`ReportId` or `ReportName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves Report details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricReportDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricReportDefinition.md new file mode 100644 index 0000000..99e3b50 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricReportDefinition.md @@ -0,0 +1,58 @@ +# Get-FabricReportDefinition + +## Overview + +The `Get-FabricReportDefinition` function retrieves the definition of a report from a specific workspace in Microsoft Fabric. + +## Description + +This function fetches the report's content or metadata from a workspace. It supports retrieving report definitions in various formats, handling both synchronous and asynchronous operations, with detailed logging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the report exists. +- **Type:** String +- **Mandatory:** Yes + +### ReportId + +- **Description:** The unique identifier of the report whose definition needs to be retrieved. +- **Type:** String +- **Mandatory:** No + +### ReportFormat + +- **Description:** Specifies the format of the report definition. This parameter is optional. +- **Type:** String +- **Mandatory:** No + +## Examples + +### Example 1: Retrieve a Report Definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$report = Get-FabricReport -WorkspaceId $workspace.id -ReportName "Report-12345" +Get-FabricReportDefinition -WorkspaceId $workspace.id -ReportId $report.id +``` + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, `ReportId`, and `ReportFormat` (if provided). +3. Sends a POST request to retrieve the report definition. +4. Handles both immediate responses and long-running operations. +5. Validates the API response and processes the definition. + +## Error Handling + +- Logs descriptive error messages for failed API requests or invalid inputs. +- Returns `null` for any errors encountered during execution. +- Handles long-running operations and retries if necessary. + +## Author + +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Get-FabricSQLEndpoint.md b/powershell/FabricACEToolkit/docs/Get-FabricSQLEndpoint.md new file mode 100644 index 0000000..3ff9d2c --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricSQLEndpoint.md @@ -0,0 +1,63 @@ +# Get-FabricSQLEndpoint + +## Overview + +The `Get-FabricSQLEndpoint` function retrieves SQL Endpoints from a specified workspace in Fabric. It supports filtering by SQL Endpoint ID or SQL Endpoint Name. If both filters are provided, an error message is returned. The function handles token validation, API requests with continuation tokens, and processes the response to return the desired SQL Endpoint(s). + +## Features + +- Validates token expiration before making the API request. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace from which to retrieve SQL Endpoints. +- **Type:** String +- **Mandatory:** Yes + +### SQLEndpointId + +- **Description:** The ID of the SQL Endpoint to retrieve. Optional, but cannot be used together with `SQLEndpointName`. +- **Type:** String +- **Mandatory:** No + +### SQLEndpointName + +- **Description:** The name of the SQL Endpoint to retrieve. Optional, but cannot be used together with `SQLEndpointId`. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve a list of SQL Endpoint + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace123" +Get-FabricSqlEndpoint -WorkspaceId $workspace.id + +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates token validity using `Test-TokenExpired`. +2. Constructs the API URL and retrieves SQL Endpoints using paginated responses if needed. +3. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricSemanticModel.md b/powershell/FabricACEToolkit/docs/Get-FabricSemanticModel.md new file mode 100644 index 0000000..2b47dd6 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricSemanticModel.md @@ -0,0 +1,79 @@ +# Get-FabricSemanticModel + +## Overview + +The `Get-FabricSemanticModel` function retrieves SemanticModel details from a specified Microsoft Fabric workspace using either the provided SemanticModelId or SemanticModelName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by SemanticModel ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SemanticModel exists. +- **Type:** String +- **Mandatory:** Yes + +### SemanticModelId + +- **Description:** The unique identifier of the SemanticModel to retrieve. +- **Type:** String +- **Mandatory:** No + +### SemanticModelName + +- **Description:** The name of the SemanticModel to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Semantic Models + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSemanticModel -WorkspaceId $workspace.id +``` + +### Example 2: Get a Semantic Model by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelName "SM-12345" +``` + +### Example 3: Get a Semantic Model by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelId "754d670c-1df0-474e-b309-26505069dd5b" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`SemanticModelId` or `SemanticModelName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves SemanticModel details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricSemanticModelDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricSemanticModelDefinition.md new file mode 100644 index 0000000..fce5626 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricSemanticModelDefinition.md @@ -0,0 +1,57 @@ +# Get-FabricSemanticModelDefinition + +## Overview + +The `Get-FabricSemanticModelDefinition` function retrieves the definition of a SemanticModel from a specific workspace in Microsoft Fabric. + +## Description + +This function fetches the definition of a SemanticModel from a workspace using the provided `SemanticModelId`. It handles token validation, constructs the API URL, makes the API request, and processes the response. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SemanticModel exists. +- **Type:** String +- **Mandatory:** Yes + +### SemanticModelId + +- **Description:** The unique identifier of the SemanticModel to retrieve the definition for. +- **Type:** String +- **Mandatory:** No + +### SemanticModelFormat + +- **Description:** The format in which to retrieve the SemanticModel definition. +- **Type:** String +- **Mandatory:** No + +## Examples + +### Example 1: Retrieve the SemanticModel Definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$semanticModel = Get-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelName "SemanticModel-67890" +Get-FabricSemanticModelDefinition -WorkspaceId $workspace.id -SemanticModelId $semanticModel.id +``` + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SemanticModelId`. +3. Sends a POST request to retrieve the SemanticModel definition. +4. Handles both immediate responses and long-running operations. +5. Validates the API response and processes the definition. + +## Error Handling + +- Logs descriptive error messages for failed API requests or invalid inputs. +- Returns `null` for any errors encountered during execution. +- Handles long-running operations and retries if necessary. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricSparkCustomPool.md b/powershell/FabricACEToolkit/docs/Get-FabricSparkCustomPool.md new file mode 100644 index 0000000..94e6612 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricSparkCustomPool.md @@ -0,0 +1,79 @@ +# Get-FabricSparkCustomPool + +## Overview + +The `Get-FabricSparkCustomPool` function retrieves all Spark custom pools from a specified workspace in Microsoft Fabric. It handles token validation, constructs the API URL, makes the API request, and processes the response. The function supports filtering by SparkCustomPoolId or SparkCustomPoolName, but not both simultaneously. + +## Features + +- Validates token expiration before making the API request. +- Handles paginated API responses using continuation tokens. +- Supports filtering by SparkCustomPoolId or SparkCustomPoolName. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace from which to retrieve Spark custom pools. +- **Type:** String +- **Mandatory:** Yes + +### SparkCustomPoolId + +- **Description:** The ID of the specific Spark custom pool to retrieve. +- **Type:** String +- **Mandatory:** No + +### SparkCustomPoolName + +- **Description:** The name of the specific Spark custom pool to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get all Spark custom pools + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSparkCustomPool -WorkspaceId $workspace.id +``` + +### Example 2: Get a specific Spark custom pool by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSparkCustomPool -WorkspaceId $workspace.id -SparkCustomPoolId "992a9753-fb26-4dbe-8433-ccd571a2b6f2" +``` + +### Example 3: Get a specific Spark custom pool by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSparkCustomPool -WorkspaceId $workspace.id -SparkCustomPoolName "MyPool" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`SparkCustomPoolId` or `SparkCustomPoolName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves Spark custom pool details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinition.md new file mode 100644 index 0000000..e904425 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinition.md @@ -0,0 +1,79 @@ +# Get-FabricSparkJobDefinition + +## Overview + +The `Get-FabricSparkJobDefinition` function retrieves SparkJobDefinition details from a specified Microsoft Fabric workspace using either the provided SparkJobDefinitionId or SparkJobDefinitionName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by SparkJobDefinition ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SparkJobDefinition exists. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionId + +- **Description:** The unique identifier of the SparkJobDefinition to retrieve. +- **Type:** String +- **Mandatory:** No + +### SparkJobDefinitionName + +- **Description:** The name of the SparkJobDefinition to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Spark Job Definitions + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSparkJobDefinition -WorkspaceId $workspace.id +``` + +### Example 2: Get a Spark Job Definition by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionName "My SparkJobDefinition" +``` + +### Example 3: Get a Spark Job Definition by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionId "1ebac6a4-c531-4b8c-a421-4057325db497" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`SparkJobDefinitionId` or `SparkJobDefinitionName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves SparkJobDefinition details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinitionDefinition.md b/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinitionDefinition.md new file mode 100644 index 0000000..462aa15 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinitionDefinition.md @@ -0,0 +1,68 @@ +# Get-FabricSparkJobDefinitionDefinition + +## Overview + +Retrieves the definition of a SparkJobDefinition from a specified Microsoft Fabric workspace. + +## Features + +- Sends a POST request to retrieve the content or metadata of a specified SparkJobDefinition. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports different formats for the SparkJobDefinition definition. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SparkJobDefinition exists. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionId + +- **Description:** The unique identifier of the SparkJobDefinition to retrieve the definition for. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionFormat + +- **Description:** The format in which to retrieve the SparkJobDefinition definition. +- **Type:** String +- **Optional:** Yes +- **Default Value:** "SparkJobDefinitionV1" + +## Usage Examples + +### Example 1: Retrieve SparkJobDefinition Definition in default format + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$sparkJobDefinition = Get-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionName "SparkJobDefinition-67890" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SparkJobDefinitionId`. +3. Sends a POST request to the Microsoft Fabric API to retrieve the definition. +4. Handles API responses: + - `200`: SparkJobDefinition definition retrieved successfully. + - `202`: SparkJobDefinition definition retrieval request accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricSparkSettings.md b/powershell/FabricACEToolkit/docs/Get-FabricSparkSettings.md new file mode 100644 index 0000000..18ebc28 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricSparkSettings.md @@ -0,0 +1,50 @@ +# Get-FabricSparkSettings + +## Overview + +The `Get-FabricSparkSettings` function retrieves Spark settings from a specified Microsoft Fabric workspace. It handles token validation, constructs the API URL, makes the API request, and processes the response. + +## Features + +- Validates token expiration before making the API request. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which to retrieve Spark settings. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Retrieve Spark settings for a workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricSparkSettings -WorkspaceId $workspace.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates token validity using `Test-TokenExpired`. +2. Constructs the API URL and retrieves Spark settings using paginated responses if needed. +3. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricTenantSetting.md b/powershell/FabricACEToolkit/docs/Get-FabricTenantSetting.md new file mode 100644 index 0000000..80ab8b2 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricTenantSetting.md @@ -0,0 +1,56 @@ +# Get-FabricTenantSetting + +## Overview + +The `Get-FabricTenantSetting` function retrieves tenant settings for a Fabric environment by making a GET request to the appropriate API endpoint. Optionally, it filters the results by the `SettingTitle` parameter. + +## Features + +- Validates token expiration before making the API request. +- Handles API responses and processes them for tenant settings retrieval. +- Provides error handling and descriptive logging. + +## Parameters + +### SettingTitle + +- **Description:** (Optional) The title of a specific tenant setting to filter the results. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Retrieve all tenant settings + +```powershell +Get-FabricTenantSetting +``` + +### Example 2: Retrieve a specific tenant setting by title + +```powershell +Get-FabricTenantSetting -SettingTitle "SomeSetting" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates token validity using `Test-TokenExpired`. +2. Constructs the API URL and retrieves tenant settings. +3. Filters the response data based on the provided `SettingTitle` parameter. +4. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricTenantSettingOverridesCapacity.md b/powershell/FabricACEToolkit/docs/Get-FabricTenantSettingOverridesCapacity.md new file mode 100644 index 0000000..bf19e54 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricTenantSettingOverridesCapacity.md @@ -0,0 +1,47 @@ +# Get-FabricTenantSettingOverridesCapacity + +## Overview + +The `Get-FabricTenantSettingOverridesCapacity` function retrieves capacity tenant settings overrides for a Fabric tenant by making a GET request to the appropriate API endpoint. It supports handling paginated API responses using continuation tokens. + +## Features + +- Validates token expiration before making the API request. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +This function does not require any parameters. + +## Usage Examples + +### Example 1: Retrieve all capacity tenant settings overrides + +```powershell +Get-FabricTenantSettingOverridesCapacity +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates token validity using `Test-TokenExpired`. +2. Initializes variables and constructs the base API endpoint URL. +3. Iteratively retrieves capacity tenant settings overrides using continuation tokens. +4. Logs descriptive messages for debugging and error handling. +5. Aggregates and returns the data. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricWarehouse.md b/powershell/FabricACEToolkit/docs/Get-FabricWarehouse.md new file mode 100644 index 0000000..65f99aa --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricWarehouse.md @@ -0,0 +1,79 @@ +# Get-FabricWarehouse + +## Overview + +The `Get-FabricWarehouse` function retrieves warehouse details from a specified Microsoft Fabric workspace using either the provided WarehouseId or WarehouseName. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by Warehouse ID or name. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the warehouse exists. +- **Type:** String +- **Mandatory:** Yes + +### WarehouseId + +- **Description:** The unique identifier of the warehouse to retrieve. +- **Type:** String +- **Mandatory:** No + +### WarehouseName + +- **Description:** The name of the warehouse to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Warehouses + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWarehouse -WorkspaceId $workspace.id +``` + +### Example 2: Get a Warehouse by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWarehouse -WorkspaceId $workspace.id -WarehouseName "My Warehouse" +``` + +### Example 3: Get a Warehouse by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWarehouse -WorkspaceId $workspace.id -WarehouseId "12345-67890" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`WarehouseId` or `WarehouseName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves Warehouse details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Get-FabricWorkspace.md b/powershell/FabricACEToolkit/docs/Get-FabricWorkspace.md new file mode 100644 index 0000000..80f7c64 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricWorkspace.md @@ -0,0 +1,73 @@ +# Get-FabricWorkspace + +## Overview + +The `Get-FabricWorkspace` function retrieves workspace details from a specified Microsoft Fabric workspace using either the provided `WorkspaceId` or `WorkspaceName`. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval by `WorkspaceId` or `WorkspaceName`. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### `WorkspaceId` + +- **Description:** The unique identifier of the workspace to retrieve. +- **Type:** String +- **Mandatory:** No + +### `WorkspaceName` + +- **Description:** The name of the workspace to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get a list of Workspaces + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWorkspace -WorkspaceId $workspace.id +``` + +### Example 2: Get a Workspace by name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWorkspace -WorkspaceName "My Workspace" +``` + +### Example 3: Get a Workspace by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWorkspace -WorkspaceId $workspace.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures only one filter (`WorkspaceId` or `WorkspaceName`) is provided. +2. Validates the authentication token using `Test-TokenExpired`. +3. Constructs the API URL and retrieves workspace details using paginated responses if needed. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Get-FabricWorkspaceRoleAssignment.md b/powershell/FabricACEToolkit/docs/Get-FabricWorkspaceRoleAssignment.md new file mode 100644 index 0000000..1127ad9 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Get-FabricWorkspaceRoleAssignment.md @@ -0,0 +1,67 @@ +# Get-FabricWorkspaceRoleAssignment + +## Overview + +The `Get-FabricWorkspaceRoleAssignment` function retrieves role assignments for a specified Fabric workspace. + +## Features + +- Validates token expiration before making the API request. +- Supports retrieval of all role assignments or a specific role assignment by `WorkspaceRoleAssignmentId`. +- Handles paginated API responses using continuation tokens. +- Provides error handling and descriptive logging. + +## Parameters + +### `WorkspaceId` + +- **Description:** The unique identifier of the workspace to fetch role assignments for. +- **Type:** String +- **Mandatory:** Yes + +### `WorkspaceRoleAssignmentId` + +- **Description:** (Optional) The unique identifier of a specific role assignment to retrieve. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Get all role assignments for a workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWorkspaceRoleAssignment -WorkspaceId $workspace.id + +``` + +### Example 2: Get a specific role assignment by ID + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWorkspaceRoleAssignment -WorkspaceId $workspace.id -WorkspaceRoleAssignmentId "9999999999-9999-9999-9999-9999999999" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Ensures token validity using `Test-TokenExpired`. +2. Constructs the API URL to fetch role assignments. +3. Retrieves role assignments using paginated responses if necessary. +4. Filters the response data based on the provided parameters. +5. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Load-FabricLakehouseTable.md b/powershell/FabricACEToolkit/docs/Load-FabricLakehouseTable.md new file mode 100644 index 0000000..7fb8130 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Load-FabricLakehouseTable.md @@ -0,0 +1,141 @@ +# Load-FabricLakehouseTable + +## Overview + +The `Load-FabricLakehouseTable` function is used to load data into a specified table within a Lakehouse in Microsoft Fabric. It supports loading from different file paths, file formats, and handles various loading modes like `append` and `overwrite`. + +## Description + +This function sends a POST request to the Fabric API to load data into a table within a Lakehouse. It handles CSV and Parquet file formats and manages different loading modes. The function also supports recursive loading from folders, specifying delimiter settings for CSV files, and validates the token's expiration. + +## Features + +- Ensures token validity before making API requests. +- Constructs the API URL dynamically based on provided parameters. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the Lakehouse. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseId + +- **Description:** The ID of the Lakehouse where the table resides. +- **Type:** String +- **Mandatory:** Yes + +### TableName + +- **Description:** The name of the table where data should be loaded. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric and underscores allowed. + +### PathType + +- **Description:** The type of the data path (File or Folder). +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Must be either 'File' or 'Folder'. + +### RelativePath + +- **Description:** The relative path to the data file or folder. +- **Type:** String +- **Mandatory:** Yes + +### FileFormat + +- **Description:** The format of the data (CSV or Parquet). +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Must be either 'CSV' or 'Parquet'. + +### CsvDelimiter + +- **Description:** The delimiter to use for CSV files. Default is `","`. +- **Type:** String +- **Mandatory:** No + +### CsvHeader + +- **Description:** Indicates if the CSV file has a header row. Default is `false`. +- **Type:** Boolean +- **Mandatory:** No + +### Mode + +- **Description:** The mode of data loading (`append` or `overwrite`). +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Must be either 'append' or 'overwrite'. + +### Recursive + +- **Description:** Flag to specify if loading should be recursive (only for Folder paths). +- **Type:** Boolean +- **Mandatory:** No +- **Default:** `false` + +## Usage Examples + +### Example 1:Load Table from a CSV file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "lakehouse-12345" +Load-FabricLakehouseTable ` +-WorkspaceId $workspace.id ` +-LakehouseId $lakehouse.id ` +-TableName "Table01" ` +-PathType File ` +-RelativePath "Files/test.csv" ` +-FileFormat CSV ` +-Mode overwrite ` +-CsvDelimiter "," ` +-CsvHeader $true ` +-Recursive $fals +``` + +### Example 2: Load Table from a parquet file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "lakehouse-12345" +Load-FabricLakehouseTable ` +-WorkspaceId $workspace.id ` +-LakehouseId $lakehouse.id ` +-TableName "Table02" ` +-PathType File ` +-RelativePath "Files/test.parquet" ` +-FileFormat Parquet ` +-Mode overwrite ` +-Recursive $false +``` + +## Prerequisites + +- Ensure that `$FabricConfig.BaseUrl` and `$FabricConfig.FabricHeaders` are correctly configured with the required authentication details. +- Token validation must be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, `LakehouseId`, and `TableName`. +3. Prepares the data load request body based on parameters such as `PathType`, `RelativePath`, `FileFormat`, and `Mode`. +4. Sends the POST request to the Microsoft Fabric API to load the data. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- It includes comprehensive error handling to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricDataPipeline.md b/powershell/FabricACEToolkit/docs/New-FabricDataPipeline.md new file mode 100644 index 0000000..a6b61fa --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricDataPipeline.md @@ -0,0 +1,67 @@ +# New-FabricDataPipeline + +## Overview +The `New-FabricDataPipeline` function creates a new DataPipeline in a specified Microsoft Fabric workspace. + +## Features +- Handles token validation to ensure secure API access. +- Supports Long Running Operations. +- Provides error handling for robust operation. + +## Parameters + +### `WorkspaceId` (Mandatory) +- **Type:** `string` +- **Description:** The unique identifier of the workspace where the DataPipeline will be created. +- **Example:** `"workspace-12345"` + +### `DataPipelineName` (Mandatory) +- **Type:** `string` +- **Description:** The name of the DataPipeline to be created. +- **Validation:** Alphanumeric, spaces, and underscores. +- **Example:** `"New DataPipeline"` + +### `DataPipelineDescription` (Optional) +- **Type:** `string` +- **Description:** A description of the DataPipeline to be created. +- **Example:** `"Pipeline for data ingestion and transformation"` + +## Example Usage + +### Example 1: Create a DataPipeline with a description +```powershell +New-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineName "New DataPipeline" -DataPipelineDescription "Pipeline for ingestion" +``` + +### Example 2: Create a DataPipeline without a description +```powershell +New-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineName "New DataPipeline" +``` +This example creates a DataPipeline named "AnalyticsPipeline" in the workspace with ID "workspace-67890" and assigns it a description. + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig` , containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. +- Long-Running Operations: Utilizes `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult` for tracking status + +## Key Workflow + +1. Validate Token: Ensures the Fabric token is valid using the Test-TokenExpired function. +2. Construct API URL: Builds the API endpoint URL based on the WorkspaceId. +3. Prepare Request Body: Creates a JSON payload with the provided parameters. +4. Invoke API Call: Sends a POST request to the Fabric API to create the DataPipeline. +5. Handle Response: + 1. 201 Created: DataPipeline successfully created. + 2. 202 Accepted: Creation request accepted; handles long-running operations. + 3. Error Codes: Logs and handles unexpected response codes. +6. Return: Outputs the response from the API, including metadata about the created DataPipeline + +## Error Handling +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/New-FabricDomain.md b/powershell/FabricACEToolkit/docs/New-FabricDomain.md new file mode 100644 index 0000000..b3694d1 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricDomain.md @@ -0,0 +1,78 @@ +# New-FabricDomain + +## Overview + +The `New-FabricDomain` function creates a new domain in Microsoft Fabric by interacting with the Fabric API. This function supports adding domains with optional descriptions and parent domain associations, ensuring seamless integration with existing structures. + +## Features + +- Handles token validation to ensure secure API access. +- Supports optional parameters for domain description and parent domain association. +- Provides detailed logging of API request and response handling. + +## Parameters + +### DomainName *(Required)* + +- **Description:** The name of the domain to be created. Must only contain alphanumeric characters, underscores, and spaces. +- **Type:** String + +### DomainDescription *(Optional)* + +- **Description:** A description of the domain to be created. +- **Type:** String + +### ParentDomainId *(Optional)* + +- **Description:** The ID of the parent domain, if applicable. +- **Type:** String + +## Usage Examples + +### Example 1: Add a new domain + +```powershell +New-FabricDomain -DomainName "API1" +``` + +### Example 2: Add a new domain with description + +```powershell +New-FabricDomain -DomainName "API2" -DomainDescription "API data domain" +``` + +### Example 3: Add a new domain with description and parent domain + +```powershell +New-FabricDomain -DomainName "API3" -DomainDescription "API data domain" -ParentDomainId "2ef62c57-2e64-41fc-81c5-a80ad370172d" +``` + +### Example 4: Add a new domain parent domain + +```powershell +New-FabricDomain -DomainName "API4" -ParentDomainId "2ef62c57-2e64-41fc-81c5-a80ad370172d" +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the provided `DomainName` parameter and optional parameters. +2. Ensures the authentication token is valid. +3. Constructs the API endpoint URL and request body based on input parameters. +4. Sends a POST request to the Fabric API to create the domain. +5. Handles and logs API responses, including long-running operations if applicable. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Handles unexpected response codes and returns detailed operation results or null in case of errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricEnvironment.md b/powershell/FabricACEToolkit/docs/New-FabricEnvironment.md new file mode 100644 index 0000000..23a78cc --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricEnvironment.md @@ -0,0 +1,74 @@ +# New-FabricEnvironment + +## Overview + +Creates a new environment in a specified workspace. + +## DESCRIPTION + +The `New-FabricEnvironment` function creates a new environment within a given workspace by making a POST request to the Fabric API. This environment can optionally include a description. The function ensures token validity and handles API errors gracefully. + +## PARAMETERS + +### WorkspaceId + +- **Type**: String +- **Mandatory**: Yes +- **Description**: The unique identifier of the workspace where the environment will be created. + +### EnvironmentName + +- **Type**: String +- **Mandatory**: Yes +- **Description**: The name of the environment to be created. Only alphanumeric characters, spaces, and underscores are allowed. + +### EnvironmentDescription + +- **Type**: String +- **Mandatory**: No +- **Description**: A description of the environment. + +## Usage Examples + +### Example 1: Creating a new environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env01" +``` + +This command creates an environment named `Env01` in the workspace with ID `workspace-12345` + +### Example 2: Creating a new environment with description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName ""workspace-12345"" +New-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env02" -EnvironmentDescription "Development Environment" +``` + +This command creates an environment named `Env02` in the workspace with ID `"workspace-12345"` and adds the specified description. + +## Prerequisites + +- The global `$FabricConfig` object must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API endpoint URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Sends a GET request to the Fabric API to retrieve staging Spark compute details. +4. Validates the API response and handles errors based on status codes. +5. Returns the retrieved staging Spark compute configurations or `null` if an error occurs. + +## ERROR HANDLING + +- The function handles and logs API errors, including unexpected response codes or failed requests. +- If the operation is long-running (202 status code), the function polls for the operation status and retrieves the final result. + +## AUTHOR + +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/New-FabricEventhouse.md b/powershell/FabricACEToolkit/docs/New-FabricEventhouse.md new file mode 100644 index 0000000..375e243 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricEventhouse.md @@ -0,0 +1,89 @@ +# New-FabricEventhouse + +## Overview + +The `New-FabricEventhouse` function creates a new Eventhouse in a specified Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. It allows optional parameters to provide a description or upload definition files for the Eventhouse. + +## Features + +- Ensures token validity before making API requests. +- Constructs a customizable request body based on provided parameters. +- Supports uploading Eventhouse and platform-specific definition files. +- Handles responses, including long-running operations. + +## Usage Examples + +### Example 1: Add a new Eventhouse + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "WS API" +New-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "eventhouse-12345" +``` + +### Example 2: Add a new Eventhouse with description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "WS API" +New-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "eventhouse-67890" -EventhouseDescription "EH Events" +``` + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventhouse will be created. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseName + +- **Description:** The name of the Eventhouse to be created. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseDescription + +- **Description:** An optional description for the Eventhouse. +- **Type:** String +- **Mandatory:** No + +### EventhousePathDefinition + +- **Description:** An optional file path to the Eventhouse definition file to upload. The file content is encoded in Base64 for inclusion in the API request. +- **Type:** String +- **Mandatory:** No + +### EventhousePathPlatformDefinition + +- **Description:** An optional file path to the platform-specific definition file to upload. The file content is encoded in Base64 for inclusion in the API request. +- **Type:** String +- **Mandatory:** No + +## Prerequisites + +- Use the `Set-FabricApiHeaders` command to configure the global `$FabricConfig` variable, which must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` helper function ensures that the token is valid. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Builds a request body with optional Eventhouse and platform definition files (encoded in Base64). +4. Sends a POST request to the API endpoint. +5. Handles both immediate responses (success or failure) and long-running operations. + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for any errors encountered during execution. + +## Notes + +- Long-running operations are supported via `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult` helper functions. +- For successful operations, returns details of the created Eventhouse. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricEventstream.md b/powershell/FabricACEToolkit/docs/New-FabricEventstream.md new file mode 100644 index 0000000..527cba5 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricEventstream.md @@ -0,0 +1,89 @@ +# New-FabricEventstream + +## Overview + +The `New-FabricEventstream` function creates a new Eventstream in a specified Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. It allows optional parameters to provide a description or upload definition files for the Eventstream. + +## Features + +- Ensures token validity before making API requests. +- Constructs a customizable request body based on provided parameters. +- Supports uploading Eventstream and platform-specific definition files. +- Handles responses, including long-running operations. + +## Usage Examples + +### Example 1: Add a new Eventstream + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "WS API" +New-FabricEventstream -WorkspaceId $workspace.id -EventstreamName "Eventstream-12345" +``` + +### Example 2: Add a new Eventstream with description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "WS API" +New-FabricEventstream -WorkspaceId $workspace.id -EventstreamName "Eventstream-67890" -EventstreamDescription "EH Events" +``` + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventstream will be created. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamName + +- **Description:** The name of the Eventstream to be created. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamDescription + +- **Description:** An optional description for the Eventstream. +- **Type:** String +- **Mandatory:** No + +### EventstreamPathDefinition + +- **Description:** An optional file path to the Eventstream definition file to upload. The file content is encoded in Base64 for inclusion in the API request. +- **Type:** String +- **Mandatory:** No + +### EventstreamPathPlatformDefinition + +- **Description:** An optional file path to the platform-specific definition file to upload. The file content is encoded in Base64 for inclusion in the API request. +- **Type:** String +- **Mandatory:** No + +## Prerequisites + +- Use the `Set-FabricApiHeaders` command to configure the global `$FabricConfig` variable, which must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` helper function ensures that the token is valid. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Builds a request body with optional Eventstream and platform definition files (encoded in Base64). +4. Sends a POST request to the API endpoint. +5. Handles both immediate responses (success or failure) and long-running operations. + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for any errors encountered during execution. + +## Notes + +- Long-running operations are supported via `Get-FabricLongRunningOperation` and `Get-FabricLongRunningOperationResult` helper functions. +- For successful operations, returns details of the created Eventstream. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricKQLDashboard.md b/powershell/FabricACEToolkit/docs/New-FabricKQLDashboard.md new file mode 100644 index 0000000..b545352 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricKQLDashboard.md @@ -0,0 +1,87 @@ +# New-FabricKQLDashboard + +## Overview + +Creates a new KQLDashboard in a specified Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. This function supports optional parameters for description and path definitions for the KQLDashboard content. + +## Features + +- Creates a KQLDashboard with a specified name and optional description. +- Supports uploading KQLDashboard content and platform-specific definitions. +- Handles long-running operations for asynchronous provisioning. +- Ensures robust token validation and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the KQLDashboard will be created. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardName + +- **Description:** The name of the KQLDashboard to be created. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardDescription + +- **Description:** An optional description for the KQLDashboard. +- **Type:** String +- **Mandatory:** No + +### KQLDashboardPathDefinition + +- **Description:** An optional path to the KQLDashboard definition file (e.g., `.ipynb`) to upload. +- **Type:** String +- **Mandatory:** No + +### KQLDashboardPathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file (e.g., `.platform`) to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Add a new KQL Dashboard + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricKqlDashboard -WorkspaceId $workspace.id -KqlDashboardName "KQLDashboard-12345" +``` + +### Example 2: Add a new KQL Dashboard with Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricKqlDashboard -WorkspaceId $workspace.id -KqlDashboardName "KQLDashboard-67890" -KQLDashboardDescription "KQL Dashboard" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Builds the request body with optional content and platform definitions. +4. Sends a POST request to the Microsoft Fabric API. +5. Handles API responses: + - `201`: Dashboard created successfully. + - `202`: Dashboard creation accepted, and provisioning proceeds asynchronously. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricKQLDatabase.md b/powershell/FabricACEToolkit/docs/New-FabricKQLDatabase.md new file mode 100644 index 0000000..54eaa2a --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricKQLDatabase.md @@ -0,0 +1,117 @@ +# New-FabricKQLDatabase + +## Overview + +Creates a new KQLDatabase in a specified Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. This function supports optional parameters for description, path definitions for the KQLDatabase content, and creation payload. + +## Features + +- Creates a KQLDatabase with a specified name and optional description. +- Supports uploading KQLDatabase content and platform-specific definitions. +- Handles long-running operations for asynchronous provisioning. +- Ensures robust token validation and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the KQLDatabase will be created. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseName + +- **Description:** The name of the KQLDatabase to be created. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseDescription + +- **Description:** An optional description for the KQLDatabase. +- **Type:** String +- **Mandatory:** No + +### KQLDatabasePathDefinition + +- **Description:** An optional path to the KQLDatabase definition file (e.g., `.ipynb`) to upload. +- **Type:** String +- **Mandatory:** No + +### KQLDatabasePathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file (e.g., `.platform`) to upload. +- **Type:** String +- **Mandatory:** No + +### KQLDatabasePathSchemaDefinition + +- **Description:** An optional path to the schema definition file (e.g., `.kql`) to upload. +- **Type:** String +- **Mandatory:** No + +### KQLDatabaseType + +- **Description:** Specifies the type of KQLDatabase (`ReadWrite` or `Shortcut`). +- **Type:** String +- **Mandatory:** Yes + +### parentEventhouseId + +- **Description:** The parent eventhouse ID for ReadWrite KQLDatabase type. +- **Type:** String +- **Mandatory:** No (Required for ReadWrite type) + +### KQLInvitationToken + +- **Description:** Optional invitation token for Shortcut type. +- **Type:** String +- **Mandatory:** No (Required for Shortcut type) + +### KQLSourceClusterUri + +- **Description:** Optional source cluster URI for Shortcut type. +- **Type:** String +- **Mandatory:** No + +### KQLSourceDatabaseName + +- **Description:** Optional source database name for Shortcut type. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Add a new KQL Database + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$eventhouse = Get-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "Eventhouse-12345" +New-FabricKQLDatabase -WorkspaceId $workspace.id -KQLDatabaseName "KQLDatabase-12345" -KQLDatabaseType "ReadWrite" -parentEventhouseId $eventhouse.id +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Builds the request body with optional content, platform, and schema definitions. +4. Sends a POST request to the Microsoft Fabric API. +5. Handles API responses: + - `201`: Database created successfully. + - `202`: Database creation accepted, and provisioning proceeds asynchronously. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricKQLQueryset.md b/powershell/FabricACEToolkit/docs/New-FabricKQLQueryset.md new file mode 100644 index 0000000..2c3af5e --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricKQLQueryset.md @@ -0,0 +1,117 @@ +# New-FabricKQLQueryset + +## Overview + +Creates a new KQLQueryset in a specified Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. This function supports optional parameters for description, path definitions for the KQLQueryset content, and creation payload. + +## Features + +- Creates a KQLQueryset with a specified name and optional description. +- Supports uploading KQLQueryset content and platform-specific definitions. +- Handles long-running operations for asynchronous provisioning. +- Ensures robust token validation and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the KQLQueryset will be created. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetName + +- **Description:** The name of the KQLQueryset to be created. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetDescription + +- **Description:** An optional description for the KQLQueryset. +- **Type:** String +- **Mandatory:** No + +### KQLQuerysetPathDefinition + +- **Description:** An optional path to the KQLQueryset definition file (e.g., `.ipynb`) to upload. +- **Type:** String +- **Mandatory:** No + +### KQLQuerysetPathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file (e.g., `.platform`) to upload. +- **Type:** String +- **Mandatory:** No + +### KQLQuerysetPathSchemaDefinition + +- **Description:** An optional path to the schema definition file (e.g., `.kql`) to upload. +- **Type:** String +- **Mandatory:** No + +### KQLQuerysetType + +- **Description:** Specifies the type of KQLQueryset (`ReadWrite` or `Shortcut`). +- **Type:** String +- **Mandatory:** Yes + +### parentEventhouseId + +- **Description:** The parent eventhouse ID for ReadWrite KQLQueryset type. +- **Type:** String +- **Mandatory:** No (Required for ReadWrite type) + +### KQLInvitationToken + +- **Description:** Optional invitation token for Shortcut type. +- **Type:** String +- **Mandatory:** No (Required for Shortcut type) + +### KQLSourceClusterUri + +- **Description:** Optional source cluster URI for Shortcut type. +- **Type:** String +- **Mandatory:** No + +### KQLSourceDatabaseName + +- **Description:** Optional source database name for Shortcut type. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Add a new KQL Queryset + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$eventhouse = Get-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "Eventhouse-12345" +New-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetName "KQLQueryset-12345" -KQLQuerysetType "ReadWrite" -parentEventhouseId $eventhouse.id +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Builds the request body with optional content, platform, and schema definitions. +4. Sends a POST request to the Microsoft Fabric API. +5. Handles API responses: + - `201`: Database created successfully. + - `202`: Database creation accepted, and provisioning proceeds asynchronously. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricLakehouse.md b/powershell/FabricACEToolkit/docs/New-FabricLakehouse.md new file mode 100644 index 0000000..8f816ce --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricLakehouse.md @@ -0,0 +1,82 @@ +# New-FabricLakehouse + +## Overview + +The `New-FabricLakehouse` function creates a new Lakehouse within a specified Microsoft Fabric workspace. This function facilitates the integration of data storage and analytics by setting up a Lakehouse, with options to enable schemas and provide descriptions. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new Lakehouse in the given workspace. It supports optional parameters for adding descriptions and enabling schemas for organizing data within the Lakehouse. The function handles token validation, API request construction, and error handling. + +## Features + +- Ensures token validity before making API requests. +- Constructs the API URL dynamically based on provided parameters. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Lakehouse will be created. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseName + +- **Description:** The name of the Lakehouse to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric and underscores allowed. + +### LakehouseDescription + +- **Description:** An optional description for the Lakehouse. +- **Type:** String +- **Mandatory:** No + +### LakehouseEnableSchemas + +- **Description:** An optional parameter to enable schemas in the Lakehouse. +- **Type:** Boolean +- **Mandatory:** No +- **Default:** `false` + +## Usage Examples + +### Example 1: Create a Lakehouse without schemas + +```powershell +New-FabricLakehouse -WorkspaceId "workspace-12345" -LakehouseName "Lakehouse-12345" +``` + +### Example 2: Create a Lakehouse with schemas and description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" -LakehouseEnableSchemas $true + +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with the Lakehouse details. +4. Sends the POST request to the Microsoft Fabric API to create the Lakehouse. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricMLExperiment.md b/powershell/FabricACEToolkit/docs/New-FabricMLExperiment.md new file mode 100644 index 0000000..ded9bb1 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricMLExperiment.md @@ -0,0 +1,78 @@ +# New-FabricMLExperiment + +## Overview + +The `New-FabricMLExperiment` function creates a new ML Experiment in a specified Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. It supports optional parameters for providing a description of the ML Experiment. + +## Features + +- Validates token expiration before making the API request. +- Supports optional descriptions for the ML Experiment. +- Handles API responses, including long-running operations. +- Provides descriptive logging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the ML Experiment will be created. +- **Type:** String +- **Mandatory:** Yes + +### MLExperimentName + +- **Description:** The name of the ML Experiment to be created. +- **Type:** String +- **Mandatory:** Yes + +### MLExperimentDescription + +- **Description:** An optional description for the ML Experiment. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create an ML Experiment with a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricMLExperiment -WorkspaceId $workspace.id -MLExperimentName "MLExperiment-12345" -MLExperimentDescription "Description of the new ML Experiment" +``` + +This example creates a new ML Experiment named "MLExperiment-12345" in the workspace with name "workspace-12345" with the provided description. + +### Example 2: Create an ML Experiment without a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricMLExperiment -WorkspaceId $workspace.id -MLExperimentName "MLExperiment-67890" +``` + +This example creates a new ML Experiment named "MLExperiment-67890" in the workspace with name "workspace-12345" without providing a description. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL for creating an ML Experiment. +3. Builds the request body with the provided parameters. +4. Sends a POST request to the Microsoft Fabric API. +5. Handles API responses, including long-running operations. +6. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs detailed error messages if the API request fails or invalid input is detected. +- Handles unexpected API response codes and provides guidance for resolution. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricMLModel.md b/powershell/FabricACEToolkit/docs/New-FabricMLModel.md new file mode 100644 index 0000000..e103979 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricMLModel.md @@ -0,0 +1,78 @@ +# New-FabricMLModel + +## Overview + +The `New-FabricMLModel` function creates a new ML Model in a specified Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. It supports optional parameters for providing a description of the ML Model. + +## Features + +- Validates token expiration before making the API request. +- Supports optional descriptions for the ML Model. +- Handles API responses, including long-running operations. +- Provides descriptive logging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the ML Model will be created. +- **Type:** String +- **Mandatory:** Yes + +### MLModelName + +- **Description:** The name of the ML Model to be created. +- **Type:** String +- **Mandatory:** Yes + +### MLModelDescription + +- **Description:** An optional description for the ML Model. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create an ML Model with a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricMLModel -WorkspaceId $workspace.id -MLModelName "MLModel-12345" -MLModelDescription "Description of the new ML Model" +``` + +This example creates a new ML Model named "MLModel-12345" in the workspace with name "workspace-12345" with the provided description. + +### Example 2: Create an ML Model without a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricMLModel -WorkspaceId $workspace.id -MLModelName "MLModel-67890" +``` + +This example creates a new ML Model named "MLModel-67890" in the workspace with name "workspace-12345" without providing a description. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL for creating an ML Model. +3. Builds the request body with the provided parameters. +4. Sends a POST request to the Microsoft Fabric API. +5. Handles API responses, including long-running operations. +6. Logs descriptive messages for debugging and error handling. + +## Error Handling + +- Logs detailed error messages if the API request fails or invalid input is detected. +- Handles unexpected API response codes and provides guidance for resolution. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/New-FabricMirroredDatabase.md b/powershell/FabricACEToolkit/docs/New-FabricMirroredDatabase.md new file mode 100644 index 0000000..3b98117 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricMirroredDatabase.md @@ -0,0 +1,84 @@ +# New-FabricMirroredDatabase + +## Overview + +The `New-FabricMirroredDatabase` function creates a new MirroredDatabase within a specified workspace in Microsoft Fabric. It supports flexible configurations, including optional metadata, file-based definitions, and platform-specific settings, ensuring seamless integration with your workspace. + +## Features + +- **Token Validation:** Ensures the authentication token is valid before making the API request. +- **Custom Configurations:** Allows for optional descriptions and file-based definitions. +- **File Handling:** Supports uploading encoded MirroredDatabase and platform-specific definitions. +- **Long-Running Operation Support:** Manages asynchronous operations with real-time status updates. +- **Detailed Logging and Error Handling:** Provides comprehensive logs and error messages for troubleshooting. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the MirroredDatabase will be created. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabaseName + +- **Description:** The name of the MirroredDatabase to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Must contain only alphanumeric characters, underscores, or spaces. + +### MirroredDatabaseDescription + +- **Description:** An optional description for the MirroredDatabase. +- **Type:** String +- **Mandatory:** No + +### MirroredDatabasePathDefinition + +- **Description:** An optional path to the MirroredDatabase definition file to upload. +- **Type:** String +- **Mandatory:** No + +### MirroredDatabasePathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file to upload (e.g., `.platform`). +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create a MirroredDatabase with a definition file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricMirroredDatabase -WorkspaceId $workspace.id ` + -MirroredDatabaseName "NewMirroredDatabase" ` + -MirroredDatabasePathDefinition "C:\temp\API\MirroredDatabases\MirroredDatabaseDefinition.json" +``` + +## Prerequisites + +- **Global Configuration:** Use `Set-FabricApiHeaders` to set `$FabricConfig` with: + - `BaseUrl`: Base API endpoint for Microsoft Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- **Token Validation:** Requires `Test-TokenExpired` to check token validity. + +## Key Workflow + +1. **Token Validation:** Ensures token validity using `Test-TokenExpired`. +2. **Request Preparation:** Constructs the API request with optional configurations. +3. **API Call:** Sends a POST request to create the MirroredDatabase. +4. **Response Handling:** + - Synchronous responses (201 Created). + - Asynchronous responses (202 Accepted) with real-time operation status updates. +5. **Error Handling:** Logs errors and provides descriptive messages. + +## Error Handling + +- **Invalid Input:** Logs error messages if invalid or empty input is detected. +- **API Failures:** Handles unexpected API response codes with detailed error logging. +- **File Issues:** Validates file content before processing and logs any related issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricNotebook.md b/powershell/FabricACEToolkit/docs/New-FabricNotebook.md new file mode 100644 index 0000000..196facf --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricNotebook.md @@ -0,0 +1,99 @@ +# New-FabricNotebook + +## Overview + +The `New-FabricNotebook` function creates a new notebook within a specified Microsoft Fabric workspace. This function facilitates integrating data and analytics by setting up a notebook with options for providing descriptions and uploading notebook content. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new notebook in the given workspace. It supports optional parameters for adding descriptions and defining paths for notebook content. The function handles token validation, API request construction, and error handling. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports uploading notebook content and platform definitions. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the notebook will be created. +- **Type:** String +- **Mandatory:** Yes + +### NotebookName + +- **Description:** The name of the notebook to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters and underscores are allowed. + +### NotebookDescription + +- **Description:** An optional description for the notebook. +- **Type:** String +- **Mandatory:** No + +### NotebookPathDefinition + +- **Description:** An optional path to the notebook definition file (e.g., .ipynb file) to upload. +- **Type:** String +- **Mandatory:** No + +### NotebookPathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file (e.g., .platform file) to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create a notebook without additional content + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Notebook01" +``` + +### Example 2: Create a notebook with a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Notebook02" -NotebookDescription "Notebook" +``` + +### Example 3: Create a notebook with a content file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricNotebook ` +-WorkspaceId $workspace.id ` +-NotebookName "Notebook03" ` +-NotebookDescription "Notebook Description" ` +-NotebookPathDefinition "C:\temp\API\Notebook\SimpleExample.ipynb" +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with notebook details and optional content. +4. Sends the POST request to the Microsoft Fabric API to create the notebook. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricReflex.md b/powershell/FabricACEToolkit/docs/New-FabricReflex.md new file mode 100644 index 0000000..9a51cdf --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricReflex.md @@ -0,0 +1,99 @@ +# New-FabricReflex + +## Overview + +The `New-FabricReflex` function creates a new Reflex within a specified Microsoft Fabric workspace. This function streamlines Reflex creation by supporting descriptions and path definitions for enhanced functionality. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a Reflex in the specified workspace. It validates token authentication, constructs the necessary API request, and handles responses, including long-running operations. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports uploading Reflex definitions and platform-specific files. +- Handles long-running operations and retries. +- Logs errors for better debugging and transparency. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Reflex will be created. +- **Type:** String +- **Mandatory:** Yes + +### ReflexName + +- **Description:** The name of the Reflex to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters, spaces, and underscores are allowed. + +### ReflexDescription + +- **Description:** An optional description for the Reflex. +- **Type:** String +- **Mandatory:** No + +### ReflexPathDefinition + +- **Description:** An optional path to the Reflex definition file to upload. +- **Type:** String +- **Mandatory:** No + +### ReflexPathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create a Reflex without additional content + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricReflex -WorkspaceId $workspace.id -ReflexName "Reflex01" +``` + +### Example 2: Create a Reflex with a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricReflex -WorkspaceId $workspace.id -ReflexName "Reflex02" -ReflexDescription "Description of Reflex" +``` + +### Example 3: Create a Reflex with a content file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricReflex ` + -WorkspaceId $workspace.id ` + -ReflexName "Reflex03" ` + -ReflexDescription "Description of Reflex" ` + -ReflexPathDefinition "C:\temp\Reflex\ReflexEntities.json" +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly set with the required authentication details. +- Token validation is handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with Reflex details and optional content. +4. Sends the POST request to the Microsoft Fabric API to create the Reflex. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- Logs errors at various stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling aids in debugging and ensures robustness. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricReport.md b/powershell/FabricACEToolkit/docs/New-FabricReport.md new file mode 100644 index 0000000..4bb7d50 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricReport.md @@ -0,0 +1,82 @@ +# New-FabricReport + +## Overview + +The `New-FabricReport` function creates a new report within a specified Microsoft Fabric workspace. This function facilitates integrating data and analytics by setting up a report with options for providing descriptions and uploading report content. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new report in the given workspace. It supports optional parameters for adding descriptions and defining paths for report content. The function handles token validation, API request construction, and error handling. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports uploading report content and platform definitions. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the report will be created. +- **Type:** String +- **Mandatory:** Yes + +### ReportName + +- **Description:** The name of the report to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters and underscores are allowed. + +### ReportDescription + +- **Description:** An optional description for the report. +- **Type:** String +- **Mandatory:** No + +### ReportPathDefinition + +- **Description:** The required path to the folder containing all files for the Report definition to be uploaded. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Create a report + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricReport -WorkspaceId $workspace.id -ReportName "Report01" +``` + +### Example 2: Create a report with a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricReport -WorkspaceId $workspace.id -ReportName "Report02" -ReportDescription "Report Description" -ReportPathDefinition "C:\temp\API\Report" +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with report details and optional content. +4. Sends the POST request to the Microsoft Fabric API to create the report. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricSemanticModel.md b/powershell/FabricACEToolkit/docs/New-FabricSemanticModel.md new file mode 100644 index 0000000..84e434f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricSemanticModel.md @@ -0,0 +1,76 @@ +# New-FabricSemanticModel + +## Overview + +The `New-FabricSemanticModel` function creates a new SemanticModel in a specified Microsoft Fabric workspace. This function facilitates integrating data and analytics by setting up a SemanticModel with options for providing descriptions and uploading definition files. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new SemanticModel in the given workspace. It supports optional parameters for adding descriptions and defining paths for SemanticModel content. The function handles token validation, API request construction, and error handling. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports uploading SemanticModel content and platform definitions. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SemanticModel will be created. +- **Type:** String +- **Mandatory:** Yes + +### SemanticModelName + +- **Description:** The name of the SemanticModel to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters and underscores are allowed. + +### SemanticModelDescription + +- **Description:** An optional description for the SemanticModel. +- **Type:** String +- **Mandatory:** No + +### SemanticModelPathDefinition + +- **Description:** The required path to the folder containing all files for the Semantic Model definition to be uploaded. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Create a SemanticModel + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelName "SemanticModel-123456" -SemanticModelPathDefinition "C:\temp\API\SemanticModel" + +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with SemanticModel details and optional content. +4. Sends the POST request to the Microsoft Fabric API to create the SemanticModel. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricSparkCustomPool.md b/powershell/FabricACEToolkit/docs/New-FabricSparkCustomPool.md new file mode 100644 index 0000000..0ff5f8b --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricSparkCustomPool.md @@ -0,0 +1,123 @@ +# New-FabricSparkCustomPool + +## Overview + +The `New-FabricSparkCustomPool` function creates a new Spark custom pool in a specified Microsoft Fabric workspace. This function facilitates setting up custom Spark pools with various configurations for optimizing data processing and analytics. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new Spark custom pool in the given workspace. It supports multiple parameters for configuring the Spark pool, including node families, sizes, auto-scaling, and dynamic executor allocations. The function also includes token validation, API request construction, error handling, and logging. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports configuring Spark custom pools with options like node family, size, auto-scaling, and executor allocation. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Spark custom pool will be created. +- **Type:** String +- **Mandatory:** Yes + +### SparkCustomPoolName + +- **Description:** The name of the Spark custom pool to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters and underscores are allowed. + +### NodeFamily + +- **Description:** The family of nodes to be used in the Spark custom pool. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Must be `MemoryOptimized`. + +### NodeSize + +- **Description:** The size of the nodes to be used in the Spark custom pool. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Must be one of `Large`, `Medium`, `Small`, `XLarge`, `XXLarge`. + +### AutoScaleEnabled + +- **Description:** Specifies whether auto-scaling is enabled for the Spark custom pool. +- **Type:** Boolean +- **Mandatory:** Yes + +### AutoScaleMinNodeCount + +- **Description:** The minimum number of nodes for auto-scaling in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### AutoScaleMaxNodeCount + +- **Description:** The maximum number of nodes for auto-scaling in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### DynamicExecutorAllocationEnabled + +- **Description:** Specifies whether dynamic executor allocation is enabled for the Spark custom pool. +- **Type:** Boolean +- **Mandatory:** Yes + +### DynamicExecutorAllocationMinExecutors + +- **Description:** The minimum number of executors for dynamic executor allocation in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### DynamicExecutorAllocationMaxExecutors + +- **Description:** The maximum number of executors for dynamic executor allocation in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Create a Spark Custom Pool + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricSparkCustomPool ` +-WorkspaceId $workspace.id ` +-SparkCustomPoolName "MyPool" ` +-NodeFamily MemoryOptimized ` +-NodeSize Medium ` +-AutoScaleEnabled $true ` +-AutoScaleMinNodeCount 1 ` +-AutoScaleMaxNodeCount 2 ` +-DynamicExecutorAllocationEnabled $true ` +-DynamicExecutorAllocationMinExecutors 1 ` +-DynamicExecutorAllocationMaxExecutors 1 +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with Spark custom pool details. +4. Sends the POST request to the Microsoft Fabric API to create the Spark custom pool. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricSparkJobDefinition.md b/powershell/FabricACEToolkit/docs/New-FabricSparkJobDefinition.md new file mode 100644 index 0000000..19a031a --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricSparkJobDefinition.md @@ -0,0 +1,85 @@ +# New-FabricSparkJobDefinition + +## Overview + +The `New-FabricSparkJobDefinition` function creates a new SparkJobDefinition within a specified Microsoft Fabric workspace. This function facilitates integrating data and analytics by setting up a Spark job with options for providing descriptions and uploading job definitions. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new SparkJobDefinition in the given workspace. It supports optional parameters for adding descriptions, Spark job definitions, and platform-specific definitions. The function handles token validation, API request construction, and error handling. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports uploading Spark job definitions and platform definitions. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SparkJobDefinition will be created. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionName + +- **Description:** The name of the SparkJobDefinition to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters and underscores are allowed. + +### SparkJobDefinitionDescription + +- **Description:** An optional description for the SparkJobDefinition. +- **Type:** String +- **Mandatory:** No + +### SparkJobDefinitionPathDefinition + +- **Description:** An optional path to the SparkJobDefinition definition file to upload. +- **Type:** String +- **Mandatory:** No + +### SparkJobDefinitionPathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create a SparkJobDefinition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricSparkJobDefinition ` +-WorkspaceId $workspace.id ` +-SparkJobDefinitionName "New SparkJobDefinition" ` +-SparkJobDefinitionDescription "Description of the new SparkJobDefinition" ` +-SparkJobDefinitionPathDefinition "C:\temp\API\SparkJobDefinition\Definition.json" +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with Spark job details and optional definitions. +4. Sends the POST request to the Microsoft Fabric API to create the Spark job definition. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricWarehouse.md b/powershell/FabricACEToolkit/docs/New-FabricWarehouse.md new file mode 100644 index 0000000..5e8f23e --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricWarehouse.md @@ -0,0 +1,76 @@ +# New-FabricWarehouse + +## Overview + +The `New-FabricWarehouse` function creates a new warehouse within a specified Microsoft Fabric workspace. This function simplifies the integration of data storage and management by setting up a warehouse with options for providing descriptions. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new warehouse in the given workspace. It supports optional parameters for adding descriptions. The function handles token validation, API request construction, and error handling. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports adding an optional description for the warehouse. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the warehouse will be created. +- **Type:** String +- **Mandatory:** Yes + +### WarehouseName + +- **Description:** The name of the warehouse to be created. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters, spaces, and underscores are allowed. + +### WarehouseDescription + +- **Description:** An optional description for the warehouse. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create a warehouse + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricWarehouse -WorkspaceId $workspace.id -WarehouseName "New Warehouse" +``` + +### Example 2: Create a warehouse with a description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +New-FabricWarehouse -WorkspaceId $workspace.id -WarehouseName "New Warehouse" -WarehouseDescription "Description of the new warehouse" +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`. +3. Prepares the request body with warehouse details and optional description. +4. Sends the POST request to the Microsoft Fabric API to create the warehouse. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/New-FabricWorkspace.md b/powershell/FabricACEToolkit/docs/New-FabricWorkspace.md new file mode 100644 index 0000000..50f654d --- /dev/null +++ b/powershell/FabricACEToolkit/docs/New-FabricWorkspace.md @@ -0,0 +1,81 @@ +# New-FabricWorkspace + +## Overview + +The `New-FabricWorkspace` function creates a new workspace within a specified Microsoft Fabric platform. This function simplifies the setup of a new workspace by allowing for optional descriptions and capacity configurations. + +## Description + +This function sends a POST request to the Microsoft Fabric API to create a new workspace. It handles token validation, API request construction, and response handling. + +## Features + +- Ensures token validity before making API requests. +- Dynamically constructs the API URL based on provided parameters. +- Supports adding an optional description for the workspace. +- Handles both immediate creation responses and long-running operation scenarios. +- Logs errors in case of API request failure. + +## Parameters + +### WorkspaceName + +- **Description:** The display name of the workspace to be created. Must only contain alphanumeric characters, spaces, and underscores. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only alphanumeric characters, spaces, and underscores are allowed. + +### WorkspaceDescription + +- **Description:** An optional description for the workspace. +- **Type:** String +- **Mandatory:** No + +### CapacityId + +- **Description:** An optional identifier for the capacity associated with the workspace. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Create a workspace + +```powershell +New-FabricWorkspace -WorkspaceName "workspace-12345" +``` + +### Example 2: Create a workspace with a description + +```powershell +New-FabricWorkspace -WorkspaceName "workspace-12345" -WorkspaceDescription "Description of the new workspace" +``` + +### Example 3: Create a workspace with capacity + +```powershell +$capacity = Get-FabricCapacity -capacityName "capacity-12345" +New-FabricWorkspace -WorkspaceName "workspace-12345" $capacity.id +``` + +## Prerequisites + +- Ensure that `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`, is correctly configured with the required authentication details. +- Token validation should be handled using `Test-TokenExpired`. + +## Key Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`. +3. Prepares the request body with workspace details, description (optional), and capacity (optional). +4. Sends the POST request to the Microsoft Fabric API to create the workspace. +5. Handles API responses, including long-running operations and retries. + +## Error Handling + +- The function logs errors at different stages, such as validation failures, API response errors, and unexpected statuses. +- Comprehensive error handling is included to assist in debugging. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Publish-FabricEnvironment.md b/powershell/FabricACEToolkit/docs/Publish-FabricEnvironment.md new file mode 100644 index 0000000..1c6c22b --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Publish-FabricEnvironment.md @@ -0,0 +1,60 @@ +# Publish-FabricEnvironment + +## Overview + +The `Publish-FabricEnvironment` function interacts with the Microsoft Fabric API to publish a staging environment in a specified workspace. It ensures the authentication token is valid, constructs the API request, and handles both immediate and long-running operations gracefully. + +## Features + +- Publishes a staging environment in a Microsoft Fabric workspace. +- Validates the authentication token before initiating API calls. +- Handles both synchronous and asynchronous (long-running) operations. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Required)* + +- **Description:** The unique identifier of the workspace containing the staging environment. +- **Type:** String + +### EnvironmentId *(Required)* + +- **Description:** The unique identifier of the staging environment to be published. +- **Type:** String + +## Usage Examples + +### Example 1: Publish a staging environment + +```powershell +## Publish staging environment +Publish-FabricEnvironment -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" +``` + +## Prerequisites + +- The global `$FabricConfig` object must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. **Validate Token:** Ensures the authentication token is valid using `Test-TokenExpired`. +2. **Construct API URL:** Builds the endpoint URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. **Submit API Request:** Sends a POST request to publish the staging environment. +4. **Handle Response:** + - For status code `200`: Logs and returns the publish details. + - For status code `202`: Initiates polling to track the progress of the long-running operation. +5. **Handle Long-Running Operations:** Tracks the operation status and fetches the result upon completion. +6. **Error Handling:** Logs errors and returns `null` if an unexpected response occurs. + +## Error Handling + +- Captures and logs any errors encountered during the API request. +- Handles API response codes and logs unexpected responses with detailed error messages. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/README_OLD.md b/powershell/FabricACEToolkit/docs/README_OLD.md new file mode 100644 index 0000000..1d76160 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/README_OLD.md @@ -0,0 +1,240 @@ +# FabricACEToolkit Documentation + +## Overview +The FabricACEToolkit is a collection of PowerShell scripts designed to interact with the Microsoft Fabric API. It provides functionalities to manage various resources within a Microsoft Fabric workspace, such as Spark Job Definitions, ML Models, Reports, Notebooks, and more. + +## Table of Contents +- [Installation](#installation) +- [Configuration](#configuration) +- [Functions](#functions) +- [Examples](#examples) +- [License](#license) + +## Installation +To install the FabricACEToolkit, clone the repository and import the module in your PowerShell session: +```sh +git clone https://github.com/tiagobalabuch/FabricACEToolkit.git +Import-Module ./FabricACEToolkit/FabricACEToolkit.psm1 +``` + +## Configuration +Before using the toolkit, set the Fabric Headers using the command `Set-FabricApiHeaders`. Without this you cannot call an API global variable with your API `BaseUrl` and `FabricHeaders`: + +```ps1 +Set-FabricApiHeaders -tenantId "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" +``` +## Functions + +## Root Directory +- `FabricACEToolkit.psd1` +- `FabricACEToolkit.psm1` +- `LICENSE` +- `README.md` + +## Private Directory +- `Convert-FromBase64.ps1` +- `Convert-ToBase64.ps1` +- `Get-ErrorResponse.ps1` +- `Get-FabricLongRunningOperation.ps1` +- `Get-FabricLongRunningOperationResult.ps1` +- `Get-FileDefinitionParts.ps1` +- `Is-TokenExpired-DEPRECATED.ps1` +- `Test-TokenExpired.ps1` +- `Write-Message.ps1` + +## Public Functions + +### Set-FabricApiHeaders +[Set-FabricApiHeaders.ps1](/docs/Set-FabricApiHeaders.md) + + +### Capacity +- [Get-FabricCapacity.ps1](/docs/Get-FabricCapacity.md) + +### Dashboard +- [Get-FabricDashboard.ps1](/docs/Get-FabricDashboard.md) + +### Data Pipeline +- [Get-FabricDataPipeline.ps1](/docs/Get-FabricDataPipeline.md) +- [New-FabricDataPipeline.ps1](/docs/New-FabricDataPipeline.md) +- [Remove-FabricDataPipelines.ps1](/docs/Remove-FabricDataPipeline.md) +- [Update-FabricNotebook.ps1](/docs/Update-FabricDataPipeline.md) +### Datamart +- [Get-FabricDatamart.ps1](/docs/Get-FabricDatamart.md) + +### Domain +- [Assign-FabricDomainWorkspaceByCapacity.ps1](/docs/Assign-FabricDomainWorkspaceByCapacity.md) +- `Assign-FabricDomainWorkspaceById.ps1` +- `Assign-FabricDomainWorkspaceByPrincipal.ps1` +- `Assign-FabricDomainWorkspaceRoleAssignment.ps1` +- `Get-FabricDomain.ps1` +- `Get-FabricDomainWorkspace.ps1` +- `New-FabricDomain.ps1` +- `Remove-FabricDomain.ps1` +- `Unassign-FabricDomainWorkspace.ps1` +- `Unassign-FabricDomainWorkspaceRoleAssignment.ps1` +- `Update-FabricDomain.ps1` + +### Environment +- `Get-FabricEnvironment.ps1` +- `Get-FabricEnvironmentLibrary.ps1` +- `Get-FabricEnvironmentSparkCompute.ps1` +- `Get-FabricEnvironmentStagingLibrary.ps1` +- `Get-FabricEnvironmentStagingSparkCompute.ps1` +- `New-FabricEnvironment.ps1` +- `Publish-FabricEnvironment.ps1` +- `Remove-FabricEnvironment.ps1` +- `Remove-FabricEnvironmentStagingLibrary.ps1` +- `Stop-FabricEnvironmentPublish.ps1` +- `Update-FabricEnvironment.ps1` +- `Update-FabricEnvironmentStagingSparkCompute.ps1` +- `Upload-FabricEnvironmentStagingLibrary.ps1` + +### Eventhouse +- `Get-FabricEventhouse.ps1` +- `Get-FabricEventhouseDefinition.ps1` +- `New-FabricEventhouse.ps1` +- `Remove-FabricEventhouse.ps1` +- `Update-FabricEventhouse.ps1` +- `Update-FabricEventhouseDefinition.ps1` + +### Eventstream +- `Get-FabricEventstream.ps1` +- `Get-FabricEventstreamDefinition.ps1` +- `New-FabricEventstream.ps1` +- `Remove-FabricEventstream.ps1` +- `Update-FabricEventstream.ps1` +- `Update-FabricEventstreamDefinition.ps1` + +### KQL Dashboard +- `Get-FabricKQLDashboard.ps1` +- `Get-FabricKQLDashboardDefinition.ps1` +- `New-FabricKQLDashboard.ps1` +- `Remove-FabricKQLDashboard.ps1` +- `Update-FabricKQLDashboard.ps1` +- `Update-FabricKQLDashboardDefinition.ps1` + +### KQL Database +- `Get-FabricKQLDatabase.ps1` +- `Get-FabricKQLDatabaseDefinition.ps1` +- `New-FabricKQLDatabase.ps1` +- `Remove-FabricKQLDatabase.ps1` +- `Update-FabricKQLDatabase.ps1` +- `Update-FabricKQLDatabaseDefinition.ps1` + +### KQL Queryset +- `Get-FabricKQLQueryset.ps1` +- `Get-FabricKQLQuerysetDefinition.ps1` +- `New-FabricKQLQueryset.ps1` +- `Remove-FabricKQLQueryset.ps1` +- `Update-FabricKQLQueryset.ps1` +- `Update-FabricKQLQuerysetDefinition.ps1` + +### Lakehouse +- `Get-FabricLakehouse.ps1` +- `Get-FabricLakehouseTable.ps1` +- `Load-FabricLakehouseTable.ps1` +- `New-FabricLakehouse.ps1` +- `Remove-FabricLakehouse.ps1` +- `Start-FabricLakehouseTableMaintenance.ps1` +- `Update-FabricLakehouse.ps1` + +### ML Experiment +- `Get-FabricMLExperiment.ps1` +- `New-FabricMLExperiment.ps1` +- `Remove-FabricMLExperiment.ps1` +- `Update-FabricMLExperiment.ps1` + +### ML Model +- `Get-FabricMLModel.ps1` +- `New-FabricMLModel.ps1` +- `Remove-FabricMLModel.ps1` +- `Update-FabricMLModel.ps1` + +### Mirrored Database +- `Get-FabricMirroredDatabase.ps1` +- `Get-FabricMirroredDatabaseTableStatus.ps1` +- `New-FabricMirroredDatabase.ps1` +- `Remove-FabricMirroredDatabase.ps1` +- `Update-FabricMirroredDatabase.ps1` + +### Mirrored Warehouse +- `Get-FabricMirroredWarehouse.ps1` +- `New-FabricMirroredWarehouse.ps1` +- `Remove-FabricMirroredWarehouse.ps1` +- `Update-FabricMirroredWarehouse.ps1` + +### Notebook +- `Get-FabricNotebook.ps1` +- `Get-FabricNotebookDefinition.ps1` +- `New-FabricNotebook.ps1` +- `New-FabricNotebookNEW.ps1` +- `Remove-FabricNotebook.ps1` +- `Update-FabricNotebook.ps1` +- `Update-FabricNotebookDefinition.ps1` + +### Paginated Reports +- `Get-FabricPaginatedReport.ps1` +- `Update-FabricPaginatedReport.ps1` + +### Reflex +- `Get-FabricReflex.ps1` +- `Get-FabricReflexDefinition.ps1` +- `New-FabricReflex.ps1` +- `Remove-FabricReflex.ps1` +- `Update-FabricReflex.ps1` +- `Update-FabricReflexDefinition.ps1` + +### Report +- `Get-FabricReport.ps1` +- `Get-FabricReportDefinition.ps1` +- `New-FabricReport.ps1` +- `Remove-FabricReport.ps1` +- `Update-FabricReport.ps1` +- `Update-FabricReportDefinition.ps1` + +### Semantic Model +- `Get-FabricSemanticModel.ps1` +- `New-FabricSemanticModel.ps1` +- `Remove-FabricSemanticModel.ps1` +- `Set-FabricSemanticModel.ps1` + +### Spark Job Definition +- `Get-FabricSparkJobDefinition.ps1` +- `New-FabricSparkJobDefinition.ps1` +- `Remove-FabricSparkJobDefinition.ps1` +- `Set-FabricSparkJobDefinition.ps1` + +### SQL Endpoints +- `Get-FabricSQLEndpoint.ps1` + +### Tenant +- `Get-FabricTenantSetting.ps1` +- `Get-FabricTenantSettingOverridesCapacity.ps1` + +### Warehouse +- `Get-FabricWarehouse.ps1` +- `New-FabricWarehouse.ps1` +- `Remove-FabricWarehouse.ps1` +- `Update-FabricWarehouse.ps1` + +### Workspace +- `Add-FabricWorkspaceIdentity.ps1` +- `Add-FabricWorkspaceRoleAssignment.ps1` +- `Assign-FabricWorkspaceCapacity.ps1` +- `Get-FabricWorkspace.ps1` +- `Get-FabricWorkspaceRoleAssignment.ps1` +- `New-FabricWorkspace.ps1` +- `Remove-FabricWorkspace.ps1` +- `Remove-FabricWorkspaceIdentity.ps1` +- `Remove-FabricWorkspaceRoleAssignment.ps1` +- `Unassign-FabricWorkspaceCapacity.ps1` +- `Update-FabricWorkspace.ps1` +- `Update-FabricWorkspaceRoleAssignment.ps1` + +## Examples + + + +## License +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricDataPipeline.md b/powershell/FabricACEToolkit/docs/Remove-FabricDataPipeline.md new file mode 100644 index 0000000..b1f8bf9 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricDataPipeline.md @@ -0,0 +1,54 @@ +# Remove-FabricDataPipeline + +## Overview + +The `Remove-FabricDataPipeline` function deletes a specified DataPipeline from a Microsoft Fabric workspace. It sends a DELETE request to the Fabric API to perform the operation. + +## Parameters + +### `WorkspaceId` (Mandatory) +- **Type:** `string` +- **Description:** The unique identifier of the workspace where the DataPipeline resides. +- **Example:** `"workspace-12345"` + +### `DataPipelineId` (Mandatory) +- **Type:** `string` +- **Description:** The unique identifier of the DataPipeline to be removed. +- **Example:** `"pipeline-67890"` + +## Example Usage + +### Example 1: Remove a DataPipeline +```powershell +Remove-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineId "pipeline-67890" +``` +This example deletes the DataPipeline with ID `pipeline-67890` from the workspace with ID `workspace-12345`. + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig` , containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. **Validate Token:** Ensures the Fabric token is valid using the `Test-TokenExpired` function. +2. **Construct API URL:** Builds the API endpoint URL based on the `WorkspaceId` and `DataPipelineId`. +3. **Invoke API Call:** Sends a DELETE request to the Fabric API. +4. **Handle Response:** + - **200 OK:** Confirms successful deletion. + - **Error Codes:** Logs and handles unexpected response codes. +5. **Error Handling:** Captures and logs any exceptions during the operation. + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig` , containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Notes +- Deleting a DataPipeline is irreversible. Use with caution. + +## Author + +**Author:** Tiago Balabuch \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricDomain.md b/powershell/FabricACEToolkit/docs/Remove-FabricDomain.md new file mode 100644 index 0000000..f77cf05 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricDomain.md @@ -0,0 +1,50 @@ +# Remove-FabricDomain + +## Overview + +The `Remove-FabricDomain` function removes a specified domain from Microsoft Fabric by making a DELETE request to the relevant API endpoint. + +## Features + +- Deletes a domain using its unique identifier. +- Handles token validation to ensure secure API access. +- Provides detailed logging of API request and response handling. + +## Parameters + +### DomainId *(Required)* + +- **Description:** The unique identifier of the domain to be deleted. +- **Type:** String + +## Usage Examples +### Example 1: Remove a domain + +```powershell +$domain = Get-FabricDomain -DomainName "API Updated" +Remove-FabricDomain -DomainId $domain.id +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the provided `DomainId` parameter. +2. Ensures the authentication token is valid. +3. Constructs the API endpoint URL for deleting the domain. +4. Sends a DELETE request to the Fabric API to remove the domain. +5. Handles and logs API responses, including error handling for unexpected responses. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Handles unexpected response codes and returns detailed operation results or null in case of errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricEnvironment.md b/powershell/FabricACEToolkit/docs/Remove-FabricEnvironment.md new file mode 100644 index 0000000..9ea0de1 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricEnvironment.md @@ -0,0 +1,56 @@ +# Remove-FabricEnvironment + +## Overview + +Deletes an environment from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a delete request to remove the environment. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The ID of the workspace containing the environment to delete. +- **Type:** String + +### EnvironmentId *(Mandatory)* + +- **Description:** The ID of the environment to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Creating a new environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env02" +Remove-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentId $env.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates that only one input parameter (`capacityId` or `capacityName`) is provided. +2. Ensures the authentication token is valid. +3. Retrieves capacities via the Fabric API, handling paginated responses automatically. +4. Filters results based on provided criteria or returns all capacities if no filters are applied. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricEnvironmentStagingLibrary.md b/powershell/FabricACEToolkit/docs/Remove-FabricEnvironmentStagingLibrary.md new file mode 100644 index 0000000..4614906 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricEnvironmentStagingLibrary.md @@ -0,0 +1,65 @@ +# Remove-FabricEnvironmentStagingLibrary + +## Overview + +Deletes a specified library from the staging environment in a Microsoft Fabric workspace. + +## Features + +- Sends a delete request to remove the library. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the library is to be deleted. +- **Type:** String +- **Mandatory:** Yes + +### EnvironmentId + +- **Description:** The unique identifier of the staging environment containing the library. +- **Type:** String +- **Mandatory:** Yes + +### LibraryName + +- **Description:** The name of the library to be deleted from the environment. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Creating a new environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env02" +Remove-FabricEnvironmentStagingLibrary -WorkspaceId $workspace.id -EnvironmentId $env.id -LibraryName "somelibrary.whl" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates that only one input parameter (`capacityId` or `capacityName`) is provided. +2. Ensures the authentication token is valid. +3. Constructs the API URL using `BaseUrl`, `WorkspaceId`, `EnvironmentId`, and `LibraryName`. +4. Sends a DELETE request to remove the library from the staging environment. +5. Handles the API response to check for success or error. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricEventhouse.md b/powershell/FabricACEToolkit/docs/Remove-FabricEventhouse.md new file mode 100644 index 0000000..ecb8929 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricEventhouse.md @@ -0,0 +1,57 @@ + +# Remove-FabricEventhouse + +## Overview + +The `Remove-FabricEventhouse` function deletes an Eventhouse from a specified Microsoft Fabric workspace by sending a DELETE request to the Microsoft Fabric API. It uses the `WorkspaceId` and `EventhouseId` to identify the Eventhouse to be removed. + +## Features + +- Ensures token validity before making API requests. +- Constructs and sends a DELETE request to the appropriate API endpoint. +- Logs descriptive messages for debugging and error tracking. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the Eventhouse will be removed. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseId + +- **Description:** The unique identifier of the Eventhouse to be removed. +- **Type:** String +- **Mandatory:** Yes + +### Example 1: Removes an Eventhouse + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$eventhouse = Get-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "eventhouse-12345" +Remove-FabricEventhouse -WorkspaceId $workspace.id -EventhouseId $eventhouse.id +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be set up with: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` helper function ensures token validity before execution. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EventhouseId`. +3. Sends a DELETE request to the API endpoint. +4. Handles API responses and logs any errors or success messages. + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for unexpected response codes or errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricEventstream.md b/powershell/FabricACEToolkit/docs/Remove-FabricEventstream.md new file mode 100644 index 0000000..522807b --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricEventstream.md @@ -0,0 +1,56 @@ +# Remove-FabricEventstream + +## Overview + +The `Remove-FabricEventstream` function deletes an Eventstream from a specified Microsoft Fabric workspace by sending a DELETE request to the Microsoft Fabric API. It uses the `WorkspaceId` and `EventstreamId` to identify the Eventstream to be removed. + +## Features + +- Ensures token validity before making API requests. +- Constructs and sends a DELETE request to the appropriate API endpoint. +- Logs descriptive messages for debugging and error tracking. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the Eventstream will be removed. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamId + +- **Description:** The unique identifier of the Eventstream to be removed. +- **Type:** String +- **Mandatory:** Yes + +### Example 1: Removes an Eventstream + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEventstream -WorkspaceId $workspace.id -EventstreamName "Eventstream-12345" +Remove-FabricEventstream -WorkspaceId $workspace.id -EventstreamId $Eventstream.id +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be set up with: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` helper function ensures token validity before execution. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EventstreamId`. +3. Sends a DELETE request to the API endpoint. +4. Handles API responses and logs any errors or success messages. + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for unexpected response codes or errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricKQLDashboard.md b/powershell/FabricACEToolkit/docs/Remove-FabricKQLDashboard.md new file mode 100644 index 0000000..a71affc --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricKQLDashboard.md @@ -0,0 +1,56 @@ +# Remove-FabricKQLDashboard + +## Overview + +The `Remove-FabricKQLDashboard` function deletes an KQLDashboard from a specified Microsoft Fabric workspace by sending a DELETE request to the Microsoft Fabric API. It uses the `WorkspaceId` and `KQLDashboardId` to identify the KQLDashboard to be removed. + +## Features + +- Ensures token validity before making API requests. +- Constructs and sends a DELETE request to the appropriate API endpoint. +- Logs descriptive messages for debugging and error tracking. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace from which the KQLDashboard will be removed. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardId + +- **Description:** The unique identifier of the KQLDashboard to be removed. +- **Type:** String +- **Mandatory:** Yes + +### Example 1: Removes a KQL Dashboard + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$KQLDashboard = Get-FabricKQLDashboard -WorkspaceId $workspace.id -KQLDashboardName "KQLDashboard-12345" +Remove-FabricKQLDashboard -WorkspaceId $workspace.id -KQLDashboardId $KQLDashboard.id +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be set up with: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` helper function ensures token validity before execution. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `KQLDashboardId`. +3. Sends a DELETE request to the API endpoint. +4. Handles API responses and logs any errors or success messages. + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for unexpected response codes or errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricKQLDatabase.md b/powershell/FabricACEToolkit/docs/Remove-FabricKQLDatabase.md new file mode 100644 index 0000000..fe7b461 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricKQLDatabase.md @@ -0,0 +1,60 @@ +# Remove-FabricKQLDatabase + +## Overview + +Deletes a KQLDatabase from a specified Microsoft Fabric workspace by sending a DELETE request to the Microsoft Fabric API. + +## Features + +- Sends a DELETE request to remove a specified KQLDatabase. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the KQLDatabase to delete. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseId + +- **Description:** The ID of the KQLDatabase to be deleted. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Remove a KQL Database + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$kqlDatabase = Get-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseName "KQLDB-12345" +Remove-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseId $kqlDatabase.id +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId` and `KQLDatabaseId`. +3. Sends a DELETE request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: KQLDatabase deleted successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricKQLQueryset.md b/powershell/FabricACEToolkit/docs/Remove-FabricKQLQueryset.md new file mode 100644 index 0000000..242ad77 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricKQLQueryset.md @@ -0,0 +1,60 @@ +# Remove-FabricKQLQueryset + +## Overview + +Deletes a KQLQueryset from a specified Microsoft Fabric workspace by sending a DELETE request to the Microsoft Fabric API. + +## Features + +- Sends a DELETE request to remove a specified KQLQueryset. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the KQLQueryset to delete. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetId + +- **Description:** The ID of the KQLQueryset to be deleted. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Remove a KQL Query set + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$KQLQueryset = Get-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetName "KQLQuery-12345" +Remove-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetId $KQLQueryset.id +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId` and `KQLQuerysetId`. +3. Sends a DELETE request to the Microsoft Fabric API. +4. Handles API responses: + - `200`: KQLQueryset deleted successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricLakehouse.md b/powershell/FabricACEToolkit/docs/Remove-FabricLakehouse.md new file mode 100644 index 0000000..dc97eec --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricLakehouse.md @@ -0,0 +1,59 @@ +# Remove-FabricLakehouse + +## Overview + +The `Remove-FabricLakehouse` function sends a DELETE request to the Fabric API to remove a specified Lakehouse from a given workspace. + +## Features + +- Ensures token validity before making API requests. +- Constructs the API URL dynamically based on provided parameters. +- Handles responses and validates the response code. +- Logs errors in case of API request failure. + +## Usage Examples + +### Example 1: Delete a Lakehouse + +```powershell +Remove-FabricLakehouse -WorkspaceId "12345" -LakehouseId "67890" +``` + +Deletes the Lakehouse with ID "67890" from workspace "12345". + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the Lakehouse to delete. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseId + +- **Description:** The ID of the Lakehouse to be deleted. +- **Type:** String +- **Mandatory:** Yes + +## Prerequisites + +- Use the `Set-FabricApiHeaders` command to configure the global `$FabricConfig` variable, which must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` helper function ensures that the token is valid. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl` and `WorkspaceId`, `LakehouseId`. +3. Sends a DELETE request to the API endpoint. +4. Handles both immediate responses (success or failure). + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricMLExperiment.md b/powershell/FabricACEToolkit/docs/Remove-FabricMLExperiment.md new file mode 100644 index 0000000..96aa5c2 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricMLExperiment.md @@ -0,0 +1,57 @@ +# Remove-FabricMLExperiment + +## Overview + +Deletes an ML Experiment from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the ML Experiment. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the ML Experiment to delete. +- **Type:** String + +### MLExperimentId *(Mandatory)* + +- **Description:** The unique identifier of the ML Experiment to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing an ML Experiment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricMLExperiment -WorkspaceId $workspace.id -MLExperimentId "experiment-67890" +``` + +This example removes the ML Experiment with ID `experiment-67890` from the workspace with name `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified ML Experiment. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricMLModel.md b/powershell/FabricACEToolkit/docs/Remove-FabricMLModel.md new file mode 100644 index 0000000..ddf7037 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricMLModel.md @@ -0,0 +1,57 @@ +# Remove-FabricMLModel + +## Overview + +Deletes an ML Model from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the ML Model. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the ML Model to delete. +- **Type:** String + +### MLModelId *(Mandatory)* + +- **Description:** The unique identifier of the ML Model to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing an ML Model + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricMLModel -WorkspaceId $workspace.id -MLModelId "model-67890" +``` + +This example removes the ML Model with ID `model-67890` from the workspace with name `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified ML Model. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricMirroredDatabase.md b/powershell/FabricACEToolkit/docs/Remove-FabricMirroredDatabase.md new file mode 100644 index 0000000..b4373f4 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricMirroredDatabase.md @@ -0,0 +1,56 @@ +# Remove-FabricMirroredDatabase + +## Overview + +Deletes a MirroredDatabase from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the MirroredDatabase. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The ID of the workspace containing the MirroredDatabase to delete. +- **Type:** String + +### MirroredDatabaseId *(Mandatory)* + +- **Description:** The ID of the MirroredDatabase to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Deleting a MirroredDatabase + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDWUpdated" +Remove-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates that the token is valid before making the API request. +2. Constructs the API URL using the provided `WorkspaceId` and `MirroredDatabaseId`. +3. Sends the DELETE request to the Fabric API. +4. Logs the success or error messages based on the API response. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricNotebook.md b/powershell/FabricACEToolkit/docs/Remove-FabricNotebook.md new file mode 100644 index 0000000..4c0b0ae --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricNotebook.md @@ -0,0 +1,57 @@ +# Remove-FabricNotebook + +## Overview + +Deletes a Notebook from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the Notebook. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the Notebook to delete. +- **Type:** String + +### NotebookId *(Mandatory)* + +- **Description:** The unique identifier of the Notebook to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a Notebook + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricNotebook -WorkspaceId $workspace.id -NotebookId "notebook-67890" +``` + +This example removes the Notebook with ID `notebook-67890` from the workspace with name `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified Notebook. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricReflex.md b/powershell/FabricACEToolkit/docs/Remove-FabricReflex.md new file mode 100644 index 0000000..15f4ce2 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricReflex.md @@ -0,0 +1,59 @@ +# Remove-FabricReflex + +## Overview + +Deletes a Reflex from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the Reflex. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the Reflex to delete. +- **Type:** String + +### ReflexId *(Mandatory)* + +- **Description:** The unique identifier of the Reflex to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a Reflex + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$reflex = Get-FabricReflex -WorkspaceId $workspace.id -ReflexName "Reflex-67890" +Remove-FabricReflex -WorkspaceId $workspace.id -ReflexId $reflex.id +``` + +This example removes the Reflex with ID `Reflex-67890` from the workspace `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified Reflex. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricReport.md b/powershell/FabricACEToolkit/docs/Remove-FabricReport.md new file mode 100644 index 0000000..9f5e57d --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricReport.md @@ -0,0 +1,57 @@ +# Remove-FabricReport + +## Overview + +Deletes a Report from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the Report. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the Report to delete. +- **Type:** String + +### ReportId *(Mandatory)* + +- **Description:** The unique identifier of the Report to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a Report + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricReport -WorkspaceId $workspace.id -ReportId "Report-67890" +``` + +This example removes the Report with ID `Report-67890` from the workspace with name `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified Report. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricSemanticModel.md b/powershell/FabricACEToolkit/docs/Remove-FabricSemanticModel.md new file mode 100644 index 0000000..27196ee --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricSemanticModel.md @@ -0,0 +1,56 @@ +# Remove-FabricSemanticModel + +## Overview + +Deletes a SemanticModel from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the SemanticModel. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the SemanticModel to delete. +- **Type:** String + +### SemanticModelId *(Mandatory)* + +- **Description:** The unique identifier of the SemanticModel to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a SemanticModel + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$semanticModel = Get-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelName "SemanticModel-67890" +Remove-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelId $semanticModel.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified SemanticModel. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricSparkCustomPool.md b/powershell/FabricACEToolkit/docs/Remove-FabricSparkCustomPool.md new file mode 100644 index 0000000..dd1f64d --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricSparkCustomPool.md @@ -0,0 +1,56 @@ +# Remove-FabricSparkCustomPool + +## Overview + +Deletes a Spark custom pool from a specified Microsoft Fabric workspace. + +## Features + +- Sends a DELETE request to remove the Spark custom pool. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the Spark custom pool to delete. +- **Type:** String + +### SparkCustomPoolId *(Mandatory)* + +- **Description:** The unique identifier of the Spark custom pool to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a Spark custom pool + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$pool = Get-FabricSparkCustomPool -WorkspaceId $workspace.id -SparkCustomPoolName "MyCustomPool" +Remove-FabricSparkCustomPool -WorkspaceId $workspace.id -SparkCustomPoolId $pool.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified Spark custom pool. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricSparkJobDefinition.md b/powershell/FabricACEToolkit/docs/Remove-FabricSparkJobDefinition.md new file mode 100644 index 0000000..4d13423 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricSparkJobDefinition.md @@ -0,0 +1,57 @@ +# Remove-FabricSparkJobDefinition + +## Overview + +Deletes a SparkJobDefinition from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the SparkJobDefinition. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace containing the SparkJobDefinition to delete. +- **Type:** String + +### SparkJobDefinitionId *(Mandatory)* + +- **Description:** The unique identifier of the SparkJobDefinition to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a SparkJobDefinition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionId "SparkJobDefinition-67890" +``` + +This example removes the SparkJobDefinition with ID `SparkJobDefinition-67890` from the workspace with name `workspace-12345`. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified SparkJobDefinition. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricWarehouse.md b/powershell/FabricACEToolkit/docs/Remove-FabricWarehouse.md new file mode 100644 index 0000000..3e25b5c --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricWarehouse.md @@ -0,0 +1,57 @@ +# Remove-FabricWarehouse + +## Overview + +Deletes a warehouse from a specified workspace in Microsoft Fabric. + +## Features + +- Sends a DELETE request to remove the warehouse. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace from which the warehouse will be removed. +- **Type:** String + +### WarehouseId *(Mandatory)* + +- **Description:** The unique identifier of the warehouse to be removed. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a Warehouse + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$warehouse = Get-FabricWarehouse -WorkspaceId $workspace.id -WarehouseName "warehouse-67890" +Remove-FabricWarehouse -WorkspaceId $workspace.id -WarehouseId $warehouse.id + +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided parameters. +3. Sends the DELETE request to remove the specified warehouse. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricWorkspace.md b/powershell/FabricACEToolkit/docs/Remove-FabricWorkspace.md new file mode 100644 index 0000000..a343664 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricWorkspace.md @@ -0,0 +1,50 @@ +# Remove-FabricWorkspace + +## Overview + +Deletes a workspace from Microsoft Fabric by using its workspace ID. + +## Features + +- Sends a DELETE request to remove the workspace. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace to be deleted. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a Workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricWorkspace -WorkspaceId $workspace.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided `WorkspaceId`. +3. Sends the DELETE request to remove the specified workspace. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceIdentity.md b/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceIdentity.md new file mode 100644 index 0000000..886fa7b --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceIdentity.md @@ -0,0 +1,50 @@ +# Remove-FabricWorkspaceIdentity + +## Overview + +Deprovisions the Managed Identity for a specified Fabric workspace. + +## Features + +- Sends a POST request to deprovision the Managed Identity. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace from which the identity will be removed. +- **Type:** String + +## Usage Examples + +### Example 1: Deprovisioning Managed Identity from a Workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricWorkspaceIdentity -WorkspaceId $workspace.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the POST request using the provided `WorkspaceId`. +3. Sends the POST request to deprovision the Managed Identity. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceRoleAssignment.md b/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceRoleAssignment.md new file mode 100644 index 0000000..c1ef437 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceRoleAssignment.md @@ -0,0 +1,55 @@ +# Remove-FabricWorkspaceRoleAssignment + +## Overview + +Deletes a specific role assignment from a Fabric workspace by making a DELETE request to the API. + +## Features + +- Sends a DELETE request to remove a role assignment. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace. +- **Type:** String + +### WorkspaceRoleAssignmentId *(Mandatory)* + +- **Description:** The unique identifier of the role assignment to be removed. +- **Type:** String + +## Usage Examples + +### Example 1: Removing a Role Assignment from a Workspace + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Remove-FabricWorkspaceRoleAssignment -WorkspaceId $workspace.id -WorkspaceRoleAssignmentId "99999999-9999-9999-9999-99999999999" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token's validity using `Test-TokenExpired`. +2. Constructs the API URL for the DELETE request using the provided `WorkspaceId` and `WorkspaceRoleAssignmentId`. +3. Sends the DELETE request to remove the specified role assignment. +4. Logs detailed responses and errors for debugging purposes. + +## Error Handling + +- Logs descriptive error messages if the API request fails or invalid input is detected. +- Returns `null` if an error occurs during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Set-FabricApiHeaders.md b/powershell/FabricACEToolkit/docs/Set-FabricApiHeaders.md new file mode 100644 index 0000000..9611a6a --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Set-FabricApiHeaders.md @@ -0,0 +1,76 @@ +# Set-FabricApiHeaders + +## Overview + +The `Set-FabricApiHeaders` function configures the Fabric API headers by logging into a specified Azure tenant, retrieving an access token, and updating the global configuration for subsequent API requests. It supports both service principal and user-based authentication methods. + +## Features + +- Logs into Azure using a tenant ID. +- Retrieves and configures the Fabric API access token. +- Supports service principal and user-based authentication. +- Updates token expiration metadata for better session management. +- Provides detailed logging and error handling. + +## Parameters + +### TenantId + +- **Description:** The Azure tenant ID for which the access token is requested. +- **Type:** String +- **Mandatory:** Yes + +### AppId + +- **Description:** The Azure app ID for the service principal. +- **Type:** String +- **Mandatory:** No + +### AppSecret + +- **Description:** The Azure app secret for the service principal. +- **Type:** SecureString +- **Mandatory:** No + +## Usage Examples + +### Example 1: Use service principal for authentication + +```powershell +$tenantId = "999999999-99999-99999-9999-999999999999" +$appId = "888888888-88888-88888-8888-888888888888" +$appSecret = "your-app-secret" +$secureAppSecret = $appSecret | ConvertTo-SecureString -AsPlainText -Force + +Set-FabricApiHeaders -TenantId $tenantId -AppId $appId -AppSecret $secureAppSecret +``` + +### Example 2: Use current user authentication + +```powershell +Set-FabricApiHeaders -TenantId "your-tenant-id" +``` + +## Prerequisites + +- The `$FabricConfig` global object must include: + - `ResourceUrl`: The base API resource URL. +- Azure PowerShell module must be installed. +- Required permissions to authenticate with the specified Azure tenant. + +## Key Workflow + +1. Validates input parameters. +2. Logs into Azure using either service principal or current user. +3. Retrieves an access token for the Fabric API. +4. Sets the token and headers in the global configuration. +5. Updates token expiration metadata. + +## Error Handling + +- Logs detailed error messages for authentication and API failures. +- Throws exceptions for invalid input or runtime errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Set-FabricHeaders.md b/powershell/FabricACEToolkit/docs/Set-FabricHeaders.md new file mode 100644 index 0000000..c1bd802 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Set-FabricHeaders.md @@ -0,0 +1,58 @@ +# Set-FabricApiHeaders + +## Overview + +The `Set-FabricApiHeaders` function facilitates interaction with the Microsoft Fabric API by setting API headers with a valid token for a specified Azure tenant. It manages authentication and ensures proper configuration for subsequent API requests. + +## Features + +- Logs in to the specified Azure tenant and retrieves an access token. +- Configures headers for Fabric API requests. +- Updates global token metadata, including expiration time and tenant ID. +- Handles errors gracefully and provides descriptive logging. + +## Parameters + +### `TenantId` *(Required)* + +- **Description:** The Azure tenant ID for which the access token is requested. +- **Type:** String + +## Usage Examples + +### Example: Configure Headers for a Specific Tenant + +```powershell +Set-FabricApiHeaders -TenantId "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +``` + +Logs in to Azure with the specified tenant ID, retrieves an access token, and configures the Fabric API headers. + +## Prerequisites + +- Azure PowerShell module Az.account must be installed and available. +- Ensure the following commands are functional: + - `Connect-AzAccount` + - `Get-AzAccessToken` + +## Key Workflow + +1. Connects to the specified Azure tenant using `Connect-AzAccount`. +2. Retrieves an access token for the Fabric API using `Get-AzAccessToken`. +3. Extracts the token and sets it as an authorization header in `$FabricConfig`. +4. Updates token expiration time and global tenant ID in `$FabricConfig`. + +## Error Handling + +- Logs detailed error messages if the function fails at any step. +- Throws an error if configuration cannot be completed due to invalid tenant or API settings. + +## Notes + +- Use `Is-TokenExpired` to validate token expiration before making API calls. +- Ensure proper permissions and configurations for Azure authentication. + +## Author + +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Start-FabricLakehouseTableMaintenance.md b/powershell/FabricACEToolkit/docs/Start-FabricLakehouseTableMaintenance.md new file mode 100644 index 0000000..583766c --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Start-FabricLakehouseTableMaintenance.md @@ -0,0 +1,169 @@ +# Start-FabricLakehouseTableMaintenance + +## Overview + +The `Start-FabricLakehouseTableMaintenance` function sends a POST request to the Fabric API to start a table maintenance job in a specified Lakehouse within a given workspace. It allows customization of the job through parameters like schema, table names, optimization settings, and retention periods. + +## Features + +- Ensures token validity before making API requests. +- Constructs the API URL dynamically based on provided parameters. +- Supports table maintenance with schema, VOrder optimization, ZOrder optimization, and retention period. +- Handles responses, including long-running operations. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the Lakehouse where the table maintenance job will be started. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseId + +- **Description:** The ID of the Lakehouse where the table maintenance job will be applied. +- **Type:** String +- **Mandatory:** Yes + +### JobType + +- **Description:** The type of job to be started. Defaults to "TableMaintenance". +- **Type:** String +- **Mandatory:** No +- **Default Value:** "TableMaintenance" + +### SchemaName + +- **Description:** Optional schema name within the Lakehouse where table maintenance will be applied. Required if the Lakehouse has schema enabled. +- **Type:** String +- **Mandatory:** No + +### TableName + +- **Description:** Optional table name where table maintenance will be applied. +- **Type:** String +- **Mandatory:** No + +### IsVOrder + +- **Description:** Optional flag to enable VOrder optimization. +- **Type:** Boolean +- **Mandatory:** No + +### ColumnsZOrderBy + +- **Description:** Optional columns to apply ZOrder optimization, comma-separated. +- **Type:** String or Array +- **Mandatory:** No + +### retentionPeriod + +- **Description:** Optional retention period for vacuuming the table, formatted as "days:hours:minutes". +- **Type:** String +- **Mandatory:** No + +### waitForCompletion + +- **Description:** Optional flag to indicate if the function should wait for the operation to complete. +- **Type:** Boolean +- **Mandatory:** No +- **Default Value:** $false + +## Usage Examples + +### Example 1: Start table maintenance withouth waiting for completion +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Start-FabricLakehouseTableMaintenance -WorkspaceId $workspace.id -LakehouseId $lakehouse.id -TableName "Table01" -Debug + +### Example 2: Start table maintenance with optimize enabled and vacuum disabled and wait for completion +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Start-FabricLakehouseTableMaintenance -WorkspaceId $workspace.id -LakehouseId $lakehouse.id -TableName "Table01" -waitForCompletion $true -Debug + +### Example 3: Start table maintenance with optimize and V-Order enabled and vacuum disabled +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Start-FabricLakehouseTableMaintenance ` +-WorkspaceId $workspace.id ` +-LakehouseId $lakehouse.id ` +-TableName "Table01" ` +-IsVOrder $true ` +-waitForCompletion $false -Debug + +### Example 4: Start table maintenance with optimize, V-Order and Z-Order with columns enabled and vacuum disabled +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Start-FabricLakehouseTableMaintenance ` +-WorkspaceId $workspace.id ` +-LakehouseId $lakehouse.id ` +-TableName "Table01" ` +-ColumnsZOrderBy @("id", "nome") ` +-waitForCompletion $false -Debug + +### Example 5: Different way to pass ColumnsZOrderBy parameter +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Start-FabricLakehouseTableMaintenance ` +-WorkspaceId $workspace.id ` +-LakehouseId $lakehouse.id ` +-TableName "Table05" ` +-IsVOrder $true ` +-ColumnsZOrderBy "id,nome" ` +-waitForCompletion $false -Debug + +### Example 6: Start table maintenance with optimize and Vaccum enabled. Retention Period must have this pattern: d:hh:mm:ss +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Start-FabricLakehouseTableMaintenance ` +-WorkspaceId $workspace.id ` +-LakehouseId $lakehouse.id ` +-TableName "Table01" ` +-retentionPeriod "1:00:00:00" ` +-waitForCompletion $false -Debug + +### Example 7: Start table maintenance with all options. Retention Period must have this pattern: d:hh:mm:ss +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Start-FabricLakehouseTableMaintenance ` +-WorkspaceId $workspace.id ` +-LakehouseId $lakehouse.id ` +-SchemaName "dbo" ` +-TableName "Table01" ` +-IsVOrder $true ` +-ColumnsZOrderBy @("id", "nome") ` +-retentionPeriod "1:00:00:00" ` +-waitForCompletion $false -Debug + + +## Prerequisites + +- Use the `Set-FabricApiHeaders` command to configure the global `$FabricConfig` variable, which must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` helper function ensures that the token is valid. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Retrieves the Lakehouse information using `Get-FabricLakehouse` to check if schema is enabled. +3. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `LakehouseId`. +4. Builds a request body with optional schema, table names, VOrder, ZOrder, and retention period. +5. Sends a POST request to the API endpoint. +6. Handles both immediate responses (success or failure) and long-running operations. + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Start-FabricMirroredDatabaseMirroring.md b/powershell/FabricACEToolkit/docs/Start-FabricMirroredDatabaseMirroring.md new file mode 100644 index 0000000..ec3b9c7 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Start-FabricMirroredDatabaseMirroring.md @@ -0,0 +1,56 @@ +# Start-FabricMirroredDatabaseMirroring + +## Overview + +Initiates the mirroring process for a MirroredDatabase in a specified workspace in Microsoft Fabric. + +## Features + +- Sends a POST request to start mirroring of the MirroredDatabase. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The ID of the workspace containing the MirroredDatabase to start mirroring. +- **Type:** String + +### MirroredDatabaseId *(Optional)* + +- **Description:** The ID of the MirroredDatabase to initiate the mirroring process. This parameter is optional. +- **Type:** String + +## Usage Examples + +### Example 1: Starting mirroring for a specific MirroredDatabase + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDW" +Start-FabricMirroredDatabaseMirroring -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates that the token is valid before making the API request. +2. Constructs the API URL using the provided `WorkspaceId` and optionally `MirroredDatabaseId`. +3. Sends the POST request to start mirroring via the Fabric API. +4. Logs the success or error messages based on the API response. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Start-FabricSparkJobDefinitionOnDemand.md b/powershell/FabricACEToolkit/docs/Start-FabricSparkJobDefinitionOnDemand.md new file mode 100644 index 0000000..92ec040 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Start-FabricSparkJobDefinitionOnDemand.md @@ -0,0 +1,79 @@ +# Start-FabricSparkJobDefinitionOnDemand + +## Overview + +The `Start-FabricSparkJobDefinitionOnDemand` function initiates a Spark Job Definition on demand within a specified workspace. It constructs the appropriate API endpoint URL and makes a POST request to start the job. The function can optionally wait for the job to complete based on the 'waitForCompletion' parameter. + +## Features + +- Ensures token validity before making API requests. +- Constructs the API URL dynamically based on provided parameters. +- Supports initiating Spark jobs with customizable job types. +- Handles responses, including long-running operations. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace where the Spark Job Definition is located. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionId + +- **Description:** The ID of the Spark Job Definition to be started. +- **Type:** String +- **Mandatory:** Yes + +### JobType + +- **Description:** The type of job to be started. Defaults to "sparkjob". +- **Type:** String +- **Mandatory:** No +- **Default Value:** "sparkjob" + +### waitForCompletion + +- **Description:** Optional flag to indicate whether to wait for the job to complete. +- **Type:** Boolean +- **Mandatory:** No +- **Default Value:** $false + +## Usage Examples + +### Example 1: Start a Spark Job Definition on demand and wait for completion + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$sparkJobDefinition = Get-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionName "SparkJobDefinition01" +Start-FabricSparkJobDefinitionOnDemand -WorkspaceId $workspace.id -SparkJobDefinitionId $sparkJobDefinition.id -waitForCompletion $true +``` + +### Example 2: Start a Spark Job Definition on demand without waiting for completion + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$sparkJobDefinition = Get-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionName "SparkJobDefinition01" +Start-FabricSparkJobDefinitionOnDemand -WorkspaceId $workspace.id -SparkJobDefinitionId $sparkJobDefinition.id -waitForCompletion $false +``` + +## Prerequisites + +- Ensure that the necessary authentication tokens are valid before running this function. +- The function logs detailed messages for debugging and informational purposes. + +## Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SparkJobDefinitionId`. +3. Makes a POST request to the API endpoint. +4. Handles both immediate responses (success or failure) and long-running operations. + +## Error Handling + +- Logs descriptive error messages for invalid inputs or failed API requests. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Stop-FabricEnvironmentPublish.md b/powershell/FabricACEToolkit/docs/Stop-FabricEnvironmentPublish.md new file mode 100644 index 0000000..2ef1623 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Stop-FabricEnvironmentPublish.md @@ -0,0 +1,58 @@ +# Stop-FabricEnvironmentPublish + +## Overview + +Cancels the publish operation for a specified environment in Microsoft Fabric. + +## Features + +- Sends a cancel publish request to the Microsoft Fabric API. +- Validates token expiration before making the API request. +- Handles both successful and error responses. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the environment exists. +- **Type:** String +- **Mandatory:** Yes + +### EnvironmentId + +- **Description:** The unique identifier of the environment for which the publish operation is to be canceled. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Cancels the publish operation for a specified environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env02" +Stop-FabricEnvironmentPublish -WorkspaceId $workspace.id -EnvironmentId $env.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Sends a POST request to cancel the publish operation. +4. Handles API responses to check for success or errors. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Stop-FabricMirroredDatabaseMirroring.md b/powershell/FabricACEToolkit/docs/Stop-FabricMirroredDatabaseMirroring.md new file mode 100644 index 0000000..4d6e4d7 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Stop-FabricMirroredDatabaseMirroring.md @@ -0,0 +1,56 @@ +# Stop-FabricMirroredDatabaseMirroring + +## Overview + +Stops the mirroring process for a MirroredDatabase in a specified workspace in Microsoft Fabric. + +## Features + +- Sends a POST request to stop mirroring of the MirroredDatabase. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The ID of the workspace containing the MirroredDatabase to stop mirroring. +- **Type:** String + +### MirroredDatabaseId *(Optional)* + +- **Description:** The ID of the MirroredDatabase to initiate stopping the mirroring process. This parameter is optional. +- **Type:** String + +## Usage Examples + +### Example 1: Stopping mirroring for a specific MirroredDatabase + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDW" +Stop-FabricMirroredDatabaseMirroring -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates that the token is valid before making the API request. +2. Constructs the API URL using the provided `WorkspaceId` and optionally `MirroredDatabaseId`. +3. Sends the POST request to stop mirroring via the Fabric API. +4. Logs the success or error messages based on the API response. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspace.md b/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspace.md new file mode 100644 index 0000000..df87cc9 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspace.md @@ -0,0 +1,56 @@ +# Unassign-FabricDomainWorkspace + +## Overview + +The `Unassign-FabricDomainWorkspace` function allows you to unassign specific workspaces from a given Fabric domain or unassign all workspaces if no workspace IDs are specified. It makes a POST request to the relevant API endpoint for this operation. + +## Features + +- Unassigns specified workspaces or all workspaces from a Fabric domain. +- Handles token validation to ensure secure API access. +- Provides detailed logging of API request and response handling. + +## Parameters + +### DomainId *(Required)* + +- **Description:** The unique identifier of the Fabric domain. +- **Type:** String + +### WorkspaceIds *(Optional)* + +- **Description:** An array of workspace IDs to unassign. If not provided, all workspaces will be unassigned. +- **Type:** Array + +## Usage Examples + +### Example 1: Unassign workspaces from a specified domain. + +```powershell +Unassign-FabricDomainWorkspace -DomainId "12345" -WorkspaceIds @("workspace1", "workspace2") +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the provided `DomainId` parameter and optional `WorkspaceIds`. +2. Ensures the authentication token is valid. +3. Constructs the API endpoint URL based on whether workspace IDs are provided. +4. Constructs the request body if workspace IDs are specified. +5. Sends a POST request to the Fabric API to unassign the specified workspaces or all workspaces. +6. Handles and logs API responses, including error handling for unexpected responses. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Handles unexpected response codes and returns detailed operation results or null in case of errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspaceRoleAssignment.md b/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspaceRoleAssignment.md new file mode 100644 index 0000000..ccc5fa1 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspaceRoleAssignment.md @@ -0,0 +1,70 @@ +# Unassign-FabricDomainWorkspaceRoleAssignment + +## Overview + +The `Unassign-FabricDomainWorkspaceRoleAssignment` function performs bulk unassignment of roles for principals in a specific Fabric domain. It sends a POST request to the relevant API endpoint. + +## Features + +- Unassigns specified roles from principals in a Fabric domain. +- Validates the structure of principal IDs. +- Handles token validation to ensure secure API access. +- Provides detailed logging of API request and response handling. + +## Parameters + +### DomainId *(Required)* + +- **Description:** The unique identifier of the Fabric domain where roles will be unassigned. +- **Type:** String + +### DomainRole *(Required)* + +- **Description:** The role to unassign from principals. Must be one of the following: + - `Admins` + - `Contributors` +- **Type:** String + +### PrincipalIds *(Required)* + +- **Description:** An array of principals to unassign roles from. Each principal must include: + - `id`: The identifier of the principal. + - `type`: The type of the principal (e.g., `User`, `Group`). +- **Type:** Array + +## Usage Examples + +### Example 1: Unassign of roles for principals in a specific Fabric domain. + +```powershell +$domain = Get-FabricDomain -DomainName "API1" +$PrincipalIds = @( @{id = "999abb4a-5555-4ac0-9c2c-bd17036fd58c"; type = "User" }, + @{id = "9999495c-6666-447a-b4d3-2d8e963e6288"; type = "User" }) +Unassign-FabricDomainWorkspaceRoleAssignment -DomainId $domain.id -DomainRole Admins -PrincipalIds $PrincipalIds +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Validates the provided `DomainId`, `DomainRole`, and `PrincipalIds` parameters. +2. Ensures each principal in `PrincipalIds` contains valid `id` and `type` properties. +3. Ensures the authentication token is valid. +4. Constructs the API endpoint URL for bulk role unassignment. +5. Constructs the request body with the domain role and principals to unassign. +6. Sends a POST request to the Fabric API to perform the bulk unassignment. +7. Handles and logs API responses, including error handling for unexpected responses. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Handles unexpected response codes and returns detailed operation results or null in case of errors. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Unassign-FabricWorkspaceCapacity.md b/powershell/FabricACEToolkit/docs/Unassign-FabricWorkspaceCapacity.md new file mode 100644 index 0000000..395cf2f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Unassign-FabricWorkspaceCapacity.md @@ -0,0 +1,58 @@ +# Unassign-FabricWorkspaceCapacity + +## Overview + +The `Unassign-FabricWorkspaceCapacity` function sends a POST request to unassign a workspace from its assigned capacity. + +## Description + +This function unassigns a specified workspace from its assigned capacity in Microsoft Fabric. It handles token validation, constructs the API request, and processes the API response. + +## Features + +- Validates authentication token using the `Test-TokenExpired` function. +- Constructs the API URL dynamically based on `WorkspaceId`. +- Supports unassigning a workspace from its specific capacity. +- Logs detailed steps for debugging and error handling. + +## Parameters + +### `WorkspaceId` *(Mandatory)* + +- **Description:** The unique identifier of the workspace to be unassigned from its capacity. +- **Type:** String + +## Usage Examples + +### Example 1: Unassign a workspace from its capacity + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Unassign-FabricWorkspaceCapacity -WorkspaceId $workspace.id +``` + +This example unassigns the workspace with ID `workspace123` from its assigned capacity. + +## Prerequisites + +- A global `$FabricConfig` object must be configured with the following properties: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be available to check token validity. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL to unassign the workspace from its capacity. +3. Sends a POST request to the API. +4. Handles different status codes, including long-running operations. +5. Returns either the result of the operation or logs the error if the operation fails. + +## Error Handling + +- Logs error messages if the API request fails or if the operation encounters issues. +- The function includes detailed logging for each major step in the process. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricDataPipeline.md b/powershell/FabricACEToolkit/docs/Update-FabricDataPipeline.md new file mode 100644 index 0000000..f9a838e --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricDataPipeline.md @@ -0,0 +1,60 @@ +# Update-FabricDataPipeline + +## Overview + +The `Update-FabricDataPipeline` function updates an existing DataPipeline in a specified Microsoft Fabric workspace. It sends a PATCH request to the Microsoft Fabric API with updated details of the DataPipeline. + +## Parameters + +### `-WorkspaceId` (Mandatory) +- **Type**: `string` +- **Description**: The unique identifier of the workspace containing the DataPipeline to be updated. +- **Example:** `"workspace-12345"` + +### `-DataPipelineId` (Mandatory) +- **Type**: `string` +- **Description**: The unique identifier of the DataPipeline to be updated. +- **Example:** `"pipeline-67890"` + +### `-DataPipelineName` (Mandatory) +- **Type**: `string` +- **Description**: The new name of the DataPipeline. +- **Validation**: Must only contain alphanumeric characters, underscores, and spaces. +- **Example:** `"My DataPipeline"` + +### `-DataPipelineDescription` +- **Type**: `string` +- **Description**: An optional updated description for the DataPipeline. + +## Example Usage + +### Example 1: Update a DataPipeline with a new name +```powershell +Update-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineId "pipeline-67890" -DataPipelineName "Updated Pipeline Name" +``` +This example updates the DataPipeline with ID `pipeline-67890` in workspace `workspace-12345` to have the name `Updated Pipeline Name`. + +### Example 2: Update a DataPipeline with a new name and description +```powershell +Update-FabricDataPipeline -WorkspaceId "workspace-12345" -DataPipelineId "pipeline-67890" -DataPipelineName "Updated Pipeline Name" -DataPipelineDescription "This is the updated description." +``` +This example updates the DataPipeline with ID `pipeline-67890` in workspace `workspace-12345` with a new name and description. + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig` , containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. **Validate Token:** Ensures the Fabric token is valid using the `Test-TokenExpired` function. +2. **Construct API URL:** Builds the API endpoint URL based on the `WorkspaceId` and `DataPipelineId`. +3. **Invoke API Call:** Sends a PATCH request to the Fabric API. +4. **Handle Response:** + - **200 OK:** Confirms successful update. + - **Error Codes:** Logs and handles unexpected response codes. +5. **Error Handling:** Captures and logs any exceptions during the operation. + +## Author +- **Name**: Tiago Balabuch diff --git a/powershell/FabricACEToolkit/docs/Update-FabricDomain.md b/powershell/FabricACEToolkit/docs/Update-FabricDomain.md new file mode 100644 index 0000000..e0c6676 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricDomain.md @@ -0,0 +1,72 @@ +# Update-FabricDomain + +## Overview + +The `Update-FabricDomain` function modifies a specified domain in Microsoft Fabric using the provided parameters. + +## Features + +- Updates the domain name, description, and contributors' scope. +- Ensures the token is valid before making API requests. +- Provides detailed logging of the API request and response handling. +- Supports optional parameters for domain description and contributors' scope. + +## Parameters + +### DomainId *(Required)* + +- **Description:** The unique identifier of the domain to be updated. +- **Type:** String + +### DomainName *(Required)* + +- **Description:** The new name for the domain. Must be alphanumeric. +- **Type:** String + +### DomainDescription *(Optional)* + +- **Description:** A new description for the domain. +- **Type:** String + +### DomainContributorsScope *(Optional)* + +- **Description:** The contributors' scope for the domain. Accepted values: + - `AdminsOnly` + - `AllTenant` + - `SpecificUsersAndGroups` +- **Type:** String + +## Usage Examples + +### Example 1: Update a domain + +```powershell +$domain = Get-FabricDomain -DomainName "API4" +Update-FabricDomain -DomainId $domain.id -DomainName "API Updated" -DomainDescription "API data domain updated" +``` + +## Prerequisites + +- The global `$FabricConfig` variable must be configured with: + - `BaseUrl`: The Fabric API base URL. + - `FabricHeaders`: Authentication headers for the API. +- The `Test-TokenExpired` function should be implemented to validate token expiration. + +## Key Workflow + +1. Ensures the provided `DomainId`, `DomainName`, and other optional parameters are valid. +2. Validates token validity before proceeding with the API request. +3. Constructs the API endpoint URL for domain update. +4. Builds the request body based on the provided parameters. +5. Sends a PATCH request to the Fabric API to perform the domain update. +6. Handles and logs API responses, including error handling for unexpected responses. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Handles unexpected response codes and returns `null` in case of errors. + +## Author + +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Update-FabricEnvironment.md b/powershell/FabricACEToolkit/docs/Update-FabricEnvironment.md new file mode 100644 index 0000000..8c0d024 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricEnvironment.md @@ -0,0 +1,64 @@ +# Update-FabricEnvironment + +## Overview + +The `Update-FabricEnvironment` function updates the name and/or description of a specified Fabric Environment by making a PATCH request to the API. + +## Features + +- Validates token expiration before making the API request. +- Constructs and sends a PATCH request to update the environment properties. +- Handles both successful and error responses. + +## Parameters + +### EnvironmentId + +- **Description:** The unique identifier of the Environment to be updated. +- **Type:** String +- **Mandatory:** Yes + +### EnvironmentName + +- **Description:** The new name for the Environment. +- **Type:** String +- **Mandatory:** Yes + +### EnvironmentDescription + +- **Description:** (Optional) The new description for the Environment. +- **Type:** String + +## Usage Examples + +### Example 1: Updates the name and/or description of a specified Fabric Environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env02" +Update-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentId $env.id -EnvironmentName "Env02 Updated" -EnvironmentDescription "Development Environment Updated" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Builds the request body with new name and optionally the description. +4. Sends a PATCH request to update the environment. +5. Validates the API response and handles results accordingly. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricEnvironmentStagingSparkCompute.md b/powershell/FabricACEToolkit/docs/Update-FabricEnvironmentStagingSparkCompute.md new file mode 100644 index 0000000..c96ba25 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricEnvironmentStagingSparkCompute.md @@ -0,0 +1,140 @@ +# Update-FabricEnvironmentStagingSparkCompute + +## Overview + +The `Update-FabricEnvironmentStagingSparkCompute` function sends a PATCH request to the Microsoft Fabric API to update the Spark compute settings for a specified environment in the staging workspace. + +## Features + +- Validates token expiration before making the API request. +- Constructs and sends a PATCH request to update Spark compute configurations. +- Handles successful and error responses. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the environment exists. +- **Type:** String +- **Mandatory:** Yes + +### EnvironmentId + +- **Description:** The unique identifier of the environment where the Spark compute settings will be updated. +- **Type:** String +- **Mandatory:** Yes + +### InstancePoolName + +- **Description:** The name of the instance pool to be used for Spark compute. +- **Type:** String +- **Mandatory:** Yes + +### InstancePoolType + +- **Description:** The type of instance pool (either 'Workspace' or 'Capacity'). +- **Type:** String +- **Mandatory:** Yes + +### DriverCores + +- **Description:** The number of cores to allocate to the driver. +- **Type:** Integer +- **Mandatory:** Yes + +### DriverMemory + +- **Description:** The amount of memory to allocate to the driver. +- **Type:** String +- **Mandatory:** Yes + +### ExecutorCores + +- **Description:** The number of cores to allocate to each executor. +- **Type:** Integer +- **Mandatory:** Yes + +### ExecutorMemory + +- **Description:** The amount of memory to allocate to each executor. +- **Type:** String +- **Mandatory:** Yes + +### DynamicExecutorAllocationEnabled + +- **Description:** Boolean flag to enable or disable dynamic executor allocation. +- **Type:** Boolean +- **Mandatory:** Yes + +### DynamicExecutorAllocationMinExecutors + +- **Description:** The minimum number of executors when dynamic allocation is enabled. +- **Type:** Integer +- **Mandatory:** Yes + +### DynamicExecutorAllocationMaxExecutors + +- **Description:** The maximum number of executors when dynamic allocation is enabled. +- **Type:** Integer +- **Mandatory:** Yes + +### RuntimeVersion + +- **Description:** The Spark runtime version to use. +- **Type:** String +- **Mandatory:** Yes + +### SparkProperties + +- **Description:** A hashtable of additional Spark properties to configure. +- **Type:** Hashtable +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Update the Spark compute settings for a specified environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env01" +$sparkPool = Get-FabricSparkCustomPool -WorkspaceId $workspace.id -SparkCustomPoolName "MyPool" +Update-FabricEnvironmentStagingSparkCompute ` +-WorkspaceId $workspace.id ` +-EnvironmentId $env.id ` +-InstancePoolName $sparkPool.name ` +-InstancePoolType Workspace ` +-DriverCores 4 ` +-DriverMemory "28g" ` +-ExecutorCores 4 ` +-ExecutorMemory "28g" ` +-DynamicExecutorAllocationEnabled $true ` +-DynamicExecutorAllocationMinExecutors 1 ` +-DynamicExecutorAllocationMaxExecutors 1 ` +-RuntimeVersion "1.3" ` +-SparkProperties @{"spark.dynamicAllocation.executorAllocationRatio" = 1.1 } + +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Builds the request body with Spark compute configurations (instance pool, driver and executor settings, dynamic allocation, runtime version, and Spark properties). +4. Sends a PATCH request to update the Spark compute settings. +5. Validates the API response and handles results accordingly. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricEventhouse.md b/powershell/FabricACEToolkit/docs/Update-FabricEventhouse.md new file mode 100644 index 0000000..a87d01d --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricEventhouse.md @@ -0,0 +1,77 @@ +# Update-FabricEventhouse + +## Overview + +The `Update-FabricEventhouse` function updates an existing Eventhouse in a specified Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. It allows modifications to the Eventhouse's name and description. + +## Features + +- Validates the token using `Test-TokenExpired` before making the API request. +- Allows updates to the Eventhouse's name (mandatory) and description (optional). +- Provides detailed logging for debugging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventhouse exists. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseId + +- **Description:** The unique identifier of the Eventhouse to be updated. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseName + +- **Description:** The new name for the Eventhouse. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only allows alphanumeric characters, spaces, and underscores. + +### EventhouseDescription + +- **Description:** The new description for the Eventhouse. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Cancels the publish operation for a specified environment + +```powershell +Update-FabricEventhouse ` + -WorkspaceId "workspace-12345" ` + -EventhouseId "eventhouse-67890" ` + -EventhouseName "Updated Eventhouse" ` + -EventhouseDescription "Updated description" +``` + +This example updates the Eventhouse with ID `eventhouse-67890` in the workspace `workspace-12345` with a new name and description. + +## Prerequisites + +- The global `$FabricConfig` variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be implemented to validate token expiry. + +## Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL based on `WorkspaceId` and `EventhouseId`. +3. Builds the request body in JSON format, including mandatory and optional parameters. +4. Sends a PATCH request to the API endpoint with the constructed JSON body. +5. Handles API responses and logs messages for debugging or error handling. + +## Error Handling + +- Logs detailed error messages for invalid inputs or failed API requests. +- Returns `null` if the API response code is not `200`. + +## Author + +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/Update-FabricEventhouseDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricEventhouseDefinition.md new file mode 100644 index 0000000..af2b856 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricEventhouseDefinition.md @@ -0,0 +1,70 @@ +# Update-FabricEventhouseDefinition + +## Overview + +This function sends a PATCH request to the Microsoft Fabric API to update the definition of an existing Eventhouse in the specified workspace. + +## Features + +- Sends a PATCH request to update the Eventhouse definition. +- Supports optional parameters for Eventhouse definition and platform-specific definition. +- Handles both successful and error responses. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventhouse exists. +- **Type:** String +- **Mandatory:** Yes + +### EventhouseId + +- **Description:** The unique identifier of the Eventhouse to be updated. +- **Type:** String +- **Mandatory:** Yes + +### EventhousePathDefinition + +- **Description:** An optional path to the Eventhouse definition file to upload. +- **Type:** String +- **Mandatory:** Yes + +### EventhousePathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Cancels the publish operation for a specified environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$eventhouse = Get-FabricEventhouse -WorkspaceId $workspace.id -EventhouseName "eventhouse-67890" +Update-FabricEventhouseDefinition -WorkspaceId $workspace.id -EventhouseId $eventhouse.id -EventhousePathDefinition "C:\temp\API\eventhouse.json" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EventhouseId`. +3. Sends a PATCH request to update the Eventhouse definition. +4. Handles API responses to check for success or errors. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricEventstream.md b/powershell/FabricACEToolkit/docs/Update-FabricEventstream.md new file mode 100644 index 0000000..48c7ba5 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricEventstream.md @@ -0,0 +1,76 @@ +# Update-FabricEventstream + +## Overview + +The `Update-FabricEventstream` function updates an existing Eventstream in a specified Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. It allows modifications to the Eventstream's name and description. + +## Features + +- Validates the token using `Test-TokenExpired` before making the API request. +- Allows updates to the Eventstream's name (mandatory) and description (optional). +- Provides detailed logging for debugging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventstream exists. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamId + +- **Description:** The unique identifier of the Eventstream to be updated. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamName + +- **Description:** The new name for the Eventstream. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only allows alphanumeric characters, spaces, and underscores. + +### EventstreamDescription + +- **Description:** The new description for the Eventstream. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Cancels the publish operation for a specified environment + +```powershell +Update-FabricEventstream ` + -WorkspaceId "workspace-12345" ` + -EventstreamId "Eventstream-67890" ` + -EventstreamName "Updated Eventstream" ` + -EventstreamDescription "Updated description" +``` + +This example updates the Eventstream with ID `Eventstream-67890` in the workspace `workspace-12345` with a new name and description. + +## Prerequisites + +- The global `$FabricConfig` variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be implemented to validate token expiry. + +## Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL based on `WorkspaceId` and `EventstreamId`. +3. Builds the request body in JSON format, including mandatory and optional parameters. +4. Sends a PATCH request to the API endpoint with the constructed JSON body. +5. Handles API responses and logs messages for debugging or error handling. + +## Error Handling + +- Logs detailed error messages for invalid inputs or failed API requests. +- Returns `null` if the API response code is not `200`. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricEventstreamDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricEventstreamDefinition.md new file mode 100644 index 0000000..e327710 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricEventstreamDefinition.md @@ -0,0 +1,70 @@ +# Update-FabricEventstreamDefinition + +## Overview + +This function sends a PATCH request to the Microsoft Fabric API to update the definition of an existing Eventstream in the specified workspace. + +## Features + +- Sends a PATCH request to update the Eventstream definition. +- Supports optional parameters for Eventstream definition and platform-specific definition. +- Handles both successful and error responses. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Eventstream exists. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamId + +- **Description:** The unique identifier of the Eventstream to be updated. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamPathDefinition + +- **Description:** An optional path to the Eventstream definition file to upload. +- **Type:** String +- **Mandatory:** Yes + +### EventstreamPathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Cancels the publish operation for a specified environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$Eventstream = Get-FabricEventstream -WorkspaceId $workspace.id -EventstreamName "Eventstream-67890" +Update-FabricEventstreamDefinition -WorkspaceId $workspace.id -EventstreamId $Eventstream.id -EventstreamPathDefinition "C:\temp\API\Eventstream.json" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EventstreamId`. +3. Sends a PATCH request to update the Eventstream definition. +4. Handles API responses to check for success or errors. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboard.md b/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboard.md new file mode 100644 index 0000000..0bef79e --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboard.md @@ -0,0 +1,75 @@ +# Update-FabricKQLDashboard + +## Overview + +Updates the properties of a specified Fabric KQLDashboard, such as its name and optional description, by making a PATCH request to the Fabric API. + +## Features + +- Supports updating the name of an existing KQLDashboard. +- Optionally updates the description of the KQLDashboard. +- Provides token validation to ensure secure API access. +- Implements robust error handling for API response validation. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace containing the KQLDashboard. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardId + +- **Description:** The unique identifier of the KQLDashboard to update. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardName + +- **Description:** The new name for the KQLDashboard. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only allows alphanumeric characters, spaces, and underscores. + +### KQLDashboardDescription + +- **Description:** An optional new description for the KQLDashboard. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a KQL Dashboard + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$kqlDashboard = Get-FabricKqlDashboard -WorkspaceId $workspace.id -KqlDashboardName "KQLDashboard-12345" +Update-FabricKqlDashboard -WorkspaceId $workspace.id -KqlDashboardId $kqlDashboard.id -KqlDashboardName "KQLDashboard-12345 Updated" -KQLDashboardDescription "KQL Dashboard Updated" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `KQLDashboardId`. +3. Builds the request body with the new `displayName` and optional `description`. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Validates the API response code: + - `200`: Indicates successful update. + - Other codes: Logs errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboardDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboardDefinition.md new file mode 100644 index 0000000..208b145 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboardDefinition.md @@ -0,0 +1,75 @@ +# Update-FabricKQLDashboardDefinition + +## Overview + +Updates the content or metadata of a KQLDashboard in a Microsoft Fabric workspace by submitting file definitions in Base64 format. This allows you to modify the dashboard's functionality or platform-specific configurations. + +## Features + +- Supports updating the primary definition file of a KQLDashboard. +- Optionally updates platform-specific definition files. +- Handles Base64 encoding of file contents for secure API submission. +- Provides support for asynchronous operations with long-running task management. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace containing the KQLDashboard. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardId + +- **Description:** The unique identifier of the KQLDashboard to update. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardPathDefinition + +- **Description:** The file path to the KQLDashboard content definition file. This file will be encoded in Base64 format before submission. +- **Type:** String +- **Mandatory:** Yes + +### KQLDashboardPathPlatformDefinition + +- **Description:** The file path to the KQLDashboard's platform-specific definition file. This file is optional and will also be encoded in Base64 format if provided. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update Dashboard Definition + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$kqlDashboard = Get-FabricKqlDashboard -WorkspaceId $workspace.id -KqlDashboardName "KQLDashboard-67890" +Update-FabricKqlDashboardDefinition -WorkspaceId $workspace.id -KqlDashboardId $kqlDashboard.id -KqlDashboardPathDefinition "C:\temp\API\kqldashboard.json" +``` +Updates the KQLDashboard content definition for the specified workspace and dashboard. + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Microsoft Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. +- Files specified in `KQLDashboardPathDefinition` and `KQLDashboardPathPlatformDefinition` must exist and contain valid content. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `KQLDashboardId`. +3. Encodes the file contents to Base64 for secure transmission. +4. Constructs the request body to include the encoded file contents. +5. Submits a POST request to the API endpoint. +6. Handles the response for synchronous and asynchronous operations. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabase.md b/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabase.md new file mode 100644 index 0000000..b214eaa --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabase.md @@ -0,0 +1,68 @@ +# Update-FabricKQLDatabase + +## Overview + +Updates the properties of a Fabric KQLDatabase by making a PATCH request to the Microsoft Fabric API. + +## Features + +- Updates the name and/or description of a specified KQLDatabase. +- Supports sending JSON-formatted updates. +- Handles long-running operations for asynchronous updates. +- Ensures robust token validation and error handling. + +## Parameters + +### KQLDatabaseId + +- **Description:** The unique identifier of the KQLDatabase to be updated. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseName + +- **Description:** The new name for the KQLDatabase. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseDescription + +- **Description:** An optional description for the KQLDatabase. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a KQL Database + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$kqlDatabase = Get-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseName "KQLDB-12345" +Update-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseId $kqlDatabase.id -KqlDatabaseName "KQLDB-12345 Updated" -KQLDatabaseDescription "KQL Database Updated" + + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `KQLDatabaseId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: KQLDatabase updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabaseDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabaseDefinition.md new file mode 100644 index 0000000..7a0f90e --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabaseDefinition.md @@ -0,0 +1,84 @@ +# Update-FabricKQLDatabaseDefinition + +## Overview + +Updates the definition of a KQLDatabase in a Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. + +## Features + +- Sends a POST request to update the content or metadata of a specified KQLDatabase. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding KQLDatabase content as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the KQLDatabase to update. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabaseId + +- **Description:** The ID of the KQLDatabase to be updated. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabasePathDefinition + +- **Description:** The file path to the KQLDatabase content definition file. The content will be encoded as Base64. +- **Type:** String +- **Mandatory:** Yes + +### KQLDatabasePathPlatformDefinition + +- **Description:** (Optional) The file path to the KQLDatabase's platform-specific definition file. +- **Type:** String +- **Mandatory:** No + +### KQLDatabasePathSchemaDefinition + +- **Description:** (Optional) The file path to the KQLDatabase's schema definition file. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update KQL KQL Queryset Content + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$kqlDatabase = Get-FabricKqlDatabase -WorkspaceId $workspace.id -KqlDatabaseName "KQLDB-12345" +Update-FabricKqlDatabaseDefinition ` +-WorkspaceId $workspace.id ` +-KqlDatabaseId $kqlDatabase.id ` +-KqlDatabasePathDefinition "C:\temp\API\KQLDatabase\KQLDatabase-definition.json" ` +-KQLDatabasePathSchemaDefinition "C:\temp\API\KQLDatabase\DatabaseSchema.kql"` +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `KQLDatabaseId`. +3. Sends a POST request to the Microsoft Fabric API with the encoded KQLDatabase content. +4. Handles API responses: + - `200`: KQLDatabase updated successfully. + - `202`: KQLDatabase update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricKQLQueryset.md b/powershell/FabricACEToolkit/docs/Update-FabricKQLQueryset.md new file mode 100644 index 0000000..d3640c1 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricKQLQueryset.md @@ -0,0 +1,68 @@ +# Update-FabricKQLQueryset + +## Overview + +Updates the properties of a Fabric KQLQueryset by making a PATCH request to the Microsoft Fabric API. + +## Features + +- Updates the name and/or description of a specified KQLQueryset. +- Supports sending JSON-formatted updates. +- Handles long-running operations for asynchronous updates. +- Ensures robust token validation and error handling. + +## Parameters + +### KQLQuerysetId + +- **Description:** The unique identifier of the KQLQueryset to be updated. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetName + +- **Description:** The new name for the KQLQueryset. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetDescription + +- **Description:** An optional description for the KQLQueryset. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a KQL Queryset + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$KQLQueryset = Get-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetName "KQLDB-12345" +Update-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetId $KQLQueryset.id -KQLQuerysetName "KQLDB-12345 Updated" -KQLQuerysetDescription "KQL Database Updated" + + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `KQLQuerysetId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: KQLQueryset updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricKQLQuerysetDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricKQLQuerysetDefinition.md new file mode 100644 index 0000000..2f5247c --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricKQLQuerysetDefinition.md @@ -0,0 +1,84 @@ +# Update-FabricKQLQuerysetDefinition + +## Overview + +Updates the definition of a KQLQueryset in a Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. + +## Features + +- Sends a POST request to update the content or metadata of a specified KQLQueryset. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding KQLQueryset content as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the KQLQueryset to update. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetId + +- **Description:** The ID of the KQLQueryset to be updated. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetPathDefinition + +- **Description:** The file path to the KQLQueryset content definition file. The content will be encoded as Base64. +- **Type:** String +- **Mandatory:** Yes + +### KQLQuerysetPathPlatformDefinition + +- **Description:** (Optional) The file path to the KQLQueryset's platform-specific definition file. +- **Type:** String +- **Mandatory:** No + +### KQLQuerysetPathSchemaDefinition + +- **Description:** (Optional) The file path to the KQLQueryset's schema definition file. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update KQL Database Content + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$KQLQueryset = Get-FabricKQLQueryset -WorkspaceId $workspace.id -KQLQuerysetName "KQLDB-12345" +Update-FabricKQLQuerysetDefinition ` +-WorkspaceId $workspace.id ` +-KQLQuerysetId $KQLQueryset.id ` +-KQLQuerysetPathDefinition "C:\temp\API\KQLQueryset\KQLQueryset-definition.json" ` +-KQLQuerysetPathSchemaDefinition "C:\temp\API\KQLQueryset\DatabaseSchema.kql"` +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `KQLQuerysetId`. +3. Sends a POST request to the Microsoft Fabric API with the encoded KQLQueryset content. +4. Handles API responses: + - `200`: KQLQueryset updated successfully. + - `202`: KQLQueryset update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricLakehouse.md b/powershell/FabricACEToolkit/docs/Update-FabricLakehouse.md new file mode 100644 index 0000000..4367cbf --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricLakehouse.md @@ -0,0 +1,67 @@ +# Update-FabricLakehouse + +## Overview + +The `Update-FabricLakehouse` function updates the name and/or description of a specified Fabric Lakehouse by making a PATCH request to the API. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace containing the Lakehouse. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseId + +- **Description:** The unique identifier of the Lakehouse to be updated. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseName + +- **Description:** The new name for the Lakehouse. +- **Type:** String +- **Mandatory:** Yes + +### LakehouseDescription + +- **Description:** An optional description for the Lakehouse. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a Lakehouse Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$lakehouse = Get-FabricLakehouse -WorkspaceId $workspace.id -LakehouseName "Lakehouse-12345" +Update-FabricLakehouse -WorkspaceId $workspace.id -LakehouseId $lakehouse.id -LakehouseName "NewLakehouseName" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `LakehouseId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: Lakehouse updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricMLExperiment.md b/powershell/FabricACEToolkit/docs/Update-FabricMLExperiment.md new file mode 100644 index 0000000..ffe48e4 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricMLExperiment.md @@ -0,0 +1,70 @@ +# Update-FabricMLExperiment + +## Overview + +Updates an existing ML Experiment in a specified Microsoft Fabric workspace. + +## Features + +- Sends a PATCH request to update the ML Experiment. +- Supports updating the ML Experiment name and description. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The ID of the workspace containing the ML Experiment to update. +- **Type:** String + +### MLExperimentId *(Mandatory)* + +- **Description:** The ID of the ML Experiment to update. +- **Type:** String + +### MLExperimentName *(Mandatory)* + +- **Description:** The new name of the ML Experiment. +- **Type:** String +- **Validation:** Must contain only alphanumeric characters or underscores. + +### MLExperimentDescription *(Optional)* + +- **Description:** The new description for the ML Experiment. +- **Type:** String + +## Usage Examples + +### Example 1: Updating an ML Experiment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Update-FabricMLExperiment -WorkspaceId $workspace.id -MLExperimentId "experiment-67890" -MLExperimentName "Updated ML Experiment" -MLExperimentDescription "Updated description" +``` + +This example updates the ML Experiment with ID `experiment-67890` in the workspace with name `workspace-12345`, setting a new name and description. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates that all required parameters are provided. +2. Ensures the authentication token is valid. +3. Constructs the API URL and request body based on provided input. +4. Sends a PATCH request to update the ML Experiment. +5. Handles errors gracefully, logging descriptive messages for debugging. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricMLModel.md b/powershell/FabricACEToolkit/docs/Update-FabricMLModel.md new file mode 100644 index 0000000..3bd14d9 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricMLModel.md @@ -0,0 +1,70 @@ +# Update-FabricMLModel + +## Overview + +Updates an existing ML Model in a specified Microsoft Fabric workspace. + +## Features + +- Sends a PATCH request to update the ML Model. +- Supports updating the ML Model name and description. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The ID of the workspace containing the ML Model to update. +- **Type:** String + +### MLModelId *(Mandatory)* + +- **Description:** The ID of the ML Model to update. +- **Type:** String + +### MLModelName *(Mandatory)* + +- **Description:** The new name of the ML Model. +- **Type:** String +- **Validation:** Must contain only alphanumeric characters or underscores. + +### MLModelDescription *(Optional)* + +- **Description:** The new description for the ML Model. +- **Type:** String + +## Usage Examples + +### Example 1: Updating an ML Model + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Update-FabricMLModel -WorkspaceId $workspace.id -MLModelId "Model-67890" -MLModelName "Updated ML Model" -MLModelDescription "Updated description" +``` + +This example updates the ML Model with ID `Model-67890` in the workspace with name `workspace-12345`, setting a new name and description. + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set the global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates that all required parameters are provided. +2. Ensures the authentication token is valid. +3. Constructs the API URL and request body based on provided input. +4. Sends a PATCH request to update the ML Model. +5. Handles errors gracefully, logging descriptive messages for debugging. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabase.md b/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabase.md new file mode 100644 index 0000000..c0200ec --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabase.md @@ -0,0 +1,67 @@ +# Update-FabricMirroredDatabase + +## Overview + +Updates the properties of a Fabric MirroredDatabase by making a PATCH request to the Fabric API. + +## Features + +- Sends a PATCH request to update the name and/or description of a MirroredDatabase. +- Validates token expiration before making the API request. +- Logs detailed messages for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The ID of the workspace containing the MirroredDatabase to be updated. +- **Type:** String + +### MirroredDatabaseId *(Mandatory)* + +- **Description:** The unique identifier of the MirroredDatabase to be updated. +- **Type:** String + +### MirroredDatabaseName *(Mandatory)* + +- **Description:** The new name for the MirroredDatabase. +- **Type:** String + +### MirroredDatabaseDescription *(Optional)* + +- **Description:** The new description for the MirroredDatabase (optional). +- **Type:** String + +## Usage Examples + +### Example 1: Updating the name of a MirroredDatabase + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDW" +Update-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id -MirroredDatabaseName "WideWorldImportersDWUpdated" -MirroredDatabaseDescription "WideWorldImportersDW Updated" +``` + +## Prerequisites + +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates token validity before making the API request. +2. Constructs the API URL using the provided `WorkspaceId` and `MirroredDatabaseId`. +3. Creates the PATCH request body, including new name and optional description. +4. Sends the PATCH request to the Fabric API. +5. Logs the success or error messages based on the API response. + +## Error Handling + +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabaseDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabaseDefinition.md new file mode 100644 index 0000000..885b714 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabaseDefinition.md @@ -0,0 +1,81 @@ +# Update-FabricMirroredDatabaseDefinition + +## Overview + +This function allows updating the content or metadata of a MirroredDatabase in a Microsoft Fabric workspace. The MirroredDatabase content can be provided as file paths, and metadata updates can optionally be enabled. + +## Features + +- Sends a POST request to update the MirroredDatabase content or metadata in a specified Microsoft Fabric workspace. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding MirroredDatabase content as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the MirroredDatabase resides. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabaseId + +- **Description:** The unique identifier of the MirroredDatabase to be updated. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabasePathDefinition + +- **Description:** The file path to the MirroredDatabase content definition file. The content will be encoded as Base64 and sent in the request. +- **Type:** String +- **Mandatory:** Yes + +### MirroredDatabasePathPlatformDefinition + +- **Description:** (Optional) The file path to the MirroredDatabase's platform-specific definition file. The content will be encoded as Base64 and sent in the request. +- **Type:** String +- **Mandatory:** No + +### UpdateMetadata + +- **Description:** (Optional) A boolean flag indicating whether to update the MirroredDatabase's metadata. Default: `$false`. +- **Type:** Boolean +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update MirroredDatabase Content + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$mirroredDatabase = Get-FabricMirroredDatabase -WorkspaceId $workspace.id -MirroredDatabaseName "WideWorldImportersDW" +Update-FabricMirroredDatabaseDefinition -WorkspaceId $workspace.id -MirroredDatabaseId $mirroredDatabase.id -MirroredDatabasePathDefinition "C:\temp\API\MirroredDatabases\MirroredDatabaseDefinition.json" + +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `MirroredDatabaseId`. +3. Sends a POST request to the Microsoft Fabric API with the encoded MirroredDatabase content. +4. Handles API responses: + - `200`: MirroredDatabase updated successfully. + - `202`: MirroredDatabase update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricNotebook.md b/powershell/FabricACEToolkit/docs/Update-FabricNotebook.md new file mode 100644 index 0000000..646aa6f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricNotebook.md @@ -0,0 +1,75 @@ +# Update-FabricNotebook + +## Overview + +The `Update-FabricNotebook` function updates the name and/or description of a specified Fabric Notebook by making a PATCH request to the API. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace containing the Notebook. +- **Type:** String +- **Mandatory:** Yes + +### NotebookId + +- **Description:** The unique identifier of the Notebook to be updated. +- **Type:** String +- **Mandatory:** Yes + +### NotebookName + +- **Description:** The new name for the Notebook. +- **Type:** String +- **Mandatory:** Yes + +### NotebookDescription + +- **Description:** An optional description for the Notebook. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a Notebook Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$notebook = Get-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Notebook-12345" +Update-FabricNotebook -WorkspaceId $workspace.id -NotebookId $notebook.id -NotebookName "NewNotebookName" +``` + +### Example 2: Update a Notebook Name and Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$notebook = Get-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Notebook-12345" +Update-FabricNotebook -WorkspaceId $workspace.id -NotebookId $notebook.id -NotebookName "NewName" -NotebookDescription "Updated description" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `NotebookId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: Notebook updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricNotebookDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricNotebookDefinition.md new file mode 100644 index 0000000..4578bb9 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricNotebookDefinition.md @@ -0,0 +1,89 @@ +# Update-FabricNotebookDefinition + +## Overview + +Updates the definition of a notebook in a Microsoft Fabric workspace by sending a POST request to the Microsoft Fabric API. + +## Features + +- Sends a POST request to update the content or metadata of a specified notebook. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding notebook content as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The ID of the workspace containing the notebook to update. +- **Type:** String +- **Mandatory:** Yes + +### NotebookId + +- **Description:** The ID of the notebook to be updated. +- **Type:** String +- **Mandatory:** Yes + +### NotebookPathDefinition + +- **Description:** The file path to the notebook content definition file. The content will be encoded as Base64. +- **Type:** String +- **Mandatory:** Yes + +### NotebookPathPlatformDefinition + +- **Description:** (Optional) The file path to the notebook's platform-specific definition file. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update Notebook Definition with a new ipynb file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$notebook = Get-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Notebook01" +Update-FabricNotebookDefinition ` + -WorkspaceId $workspace.id ` + -NotebookId $notebook.id ` + -NotebookPathDefinition "C:\temp\API\Notebook\SimpleExample.ipynb" +``` + +### Example 2: Update Notebook Definition with a new ipynb file and a new platform file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$notebook = Get-FabricNotebook -WorkspaceId $workspace.id -NotebookName "Notebook01" +Update-FabricNotebookDefinition ` + -WorkspaceId $workspace.id ` + -NotebookId $notebook.id ` + -NotebookPathDefinition "C:\temp\API\Notebook\SimpleExample.ipynb" ` + -NotebookPathPlatformDefinition "C:\temp\API\Notebook\.platform" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `NotebookId`. +3. Sends a POST request to the Microsoft Fabric API with the encoded notebook content. +4. Handles API responses: + - `200`: Notebook updated successfully. + - `202`: Notebook update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricPaginatedReport.md b/powershell/FabricACEToolkit/docs/Update-FabricPaginatedReport.md new file mode 100644 index 0000000..4dc9a0f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricPaginatedReport.md @@ -0,0 +1,67 @@ +# Update-FabricPaginatedReport + +## Overview + +The `Update-FabricPaginatedReport` function updates the name and/or description of a specified paginated report in a Microsoft Fabric workspace by making a PATCH request to the API. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace containing the paginated report. +- **Type:** String +- **Mandatory:** Yes + +### PaginatedReportId + +- **Description:** The unique identifier of the paginated report to be updated. +- **Type:** String +- **Mandatory:** Yes + +### PaginatedReportName + +- **Description:** The new name for the paginated report. +- **Type:** String +- **Mandatory:** Yes + +### PaginatedReportDescription + +- **Description:** An optional description for the paginated report. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a Paginated Report Name and Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$report = Get-FabricPaginatedReport -WorkspaceId $workspace.id -PaginatedReportName "Report-12345" +Update-FabricPaginatedReport -WorkspaceId $workspace.id -PaginatedReportId $report.id -PaginatedReportName "New Report Name" -PaginatedReportDescription "Updated description." +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `PaginatedReportId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: Paginated report updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricReflex.md b/powershell/FabricACEToolkit/docs/Update-FabricReflex.md new file mode 100644 index 0000000..0c9a45f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricReflex.md @@ -0,0 +1,75 @@ +# Update-FabricReflex + +## Overview + +The `Update-FabricReflex` function updates an existing Reflex in a specified Microsoft Fabric workspace by making a PATCH request to the API. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Reflex exists. +- **Type:** String +- **Mandatory:** Yes + +### ReflexId + +- **Description:** The unique identifier of the Reflex to be updated. +- **Type:** String +- **Mandatory:** Yes + +### ReflexName + +- **Description:** The new name of the Reflex. +- **Type:** String +- **Mandatory:** Yes + +### ReflexDescription + +- **Description:** An optional new description for the Reflex. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a Reflex Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$reflex = Get-FabricReflex -WorkspaceId $workspace.id -ReflexName "Reflex-67890" +Update-FabricReflex -WorkspaceId $workspace.id -ReflexId $reflex.id -ReflexName "Updated Reflex" +``` + +### Example 2: Update a Reflex Name and Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$reflex = Get-FabricReflex -WorkspaceId $workspace.id -ReflexName "Reflex-67890" +Update-FabricReflex -WorkspaceId $workspace.id -ReflexId $reflex.id -ReflexName "Updated Reflex" -ReflexDescription "Updated description" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `ReflexId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: Reflex updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricReflexDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricReflexDefinition.md new file mode 100644 index 0000000..e1856a8 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricReflexDefinition.md @@ -0,0 +1,77 @@ +# Update-FabricReflexDefinition + +## Overview + +Updates the definition of an existing Reflex in a Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. + +## Features + +- Sends a PATCH request to update the content or metadata of a specified Reflex. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding Reflex content as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Reflex exists. +- **Type:** String +- **Mandatory:** Yes + +### ReflexId + +- **Description:** The unique identifier of the Reflex to be updated. +- **Type:** String +- **Mandatory:** Yes + +### ReflexPathDefinition + +- **Description:** Path to the Reflex definition file to upload. +- **Type:** String +- **Mandatory:** Yes + +### ReflexPathPlatformDefinition + +- **Description:** (Optional) Path to the platform-specific definition file to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update Reflex Definition with a new JSON file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$reflex = Get-FabricReflex -WorkspaceId $workspace.id -ReflexName "Reflex01" +Update-FabricReflexDefinition ` + -WorkspaceId $workspace.id ` + -ReflexId $reflex.id ` + -ReflexPathDefinition "C:\Path\To\ReflexDefinition.json" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `ReflexId`. +3. Sends a PATCH request to the Microsoft Fabric API with the encoded Reflex content. +4. Handles API responses: + - `200`: Reflex updated successfully. + - `202`: Reflex update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricReport.md b/powershell/FabricACEToolkit/docs/Update-FabricReport.md new file mode 100644 index 0000000..c4a7346 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricReport.md @@ -0,0 +1,75 @@ +# Update-FabricReport + +## Overview + +The `Update-FabricReport` function updates the name and/or description of an existing Fabric Report by making a PATCH request to the API. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Report exists. +- **Type:** String +- **Mandatory:** No + +### ReportId + +- **Description:** The unique identifier of the Report to be updated. +- **Type:** String +- **Mandatory:** Yes + +### ReportName + +- **Description:** The new name of the Report. +- **Type:** String +- **Mandatory:** Yes + +### ReportDescription + +- **Description:** An optional new description for the Report. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a Report Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$report = Get-FabricReport -WorkspaceId $workspace.id -ReportName "Report-12345" +Update-FabricReport -WorkspaceId $workspace.id -ReportId $report.id -ReportName "UpdatedReportName" +``` + +### Example 2: Update a Report Name and Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$report = Get-FabricReport -WorkspaceId $workspace.id -ReportName "Report-12345" +Update-FabricReport -WorkspaceId $workspace.id -ReportId $report.id -ReportName "UpdatedName" -ReportDescription "Updated description" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `ReportId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: Report updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricReportDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricReportDefinition.md new file mode 100644 index 0000000..549c08e --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricReportDefinition.md @@ -0,0 +1,68 @@ +# Update-FabricReportDefinition + +## Overview + +Updates the definition of an existing Report in a Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. + +## Features + +- Sends a PATCH request to update the content or metadata of a specified Report. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding Report content as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Report exists. +- **Type:** String +- **Mandatory:** Yes + +### ReportId + +- **Description:** The unique identifier of the Report to be updated. +- **Type:** String +- **Mandatory:** Yes + +### ReportPathDefinition + +- **Description:** The required path to the folder containing all files for the Report definition to be uploaded. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Update Report Definition with a new JSON file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$report = Get-FabricReport -WorkspaceId $workspace.id -ReportName "Report-67890" +Update-FabricReportDefinition -WorkspaceId $workspace.id -ReportId $report.id -ReportPathDefinition "C:\temp\API\Report" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `ReportId`. +3. Sends a PATCH request to the Microsoft Fabric API with the encoded Report content. +4. Handles API responses: + - `200`: Report definition updated successfully. + - `202`: Report definition update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricSemanticModel.md b/powershell/FabricACEToolkit/docs/Update-FabricSemanticModel.md new file mode 100644 index 0000000..665823d --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricSemanticModel.md @@ -0,0 +1,75 @@ +# Update-FabricSemanticModel + +## Overview + +The `Update-FabricSemanticModel` function updates the name and/or description of an existing SemanticModel in a specified Microsoft Fabric workspace. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SemanticModel exists. +- **Type:** String +- **Mandatory:** No + +### SemanticModelId + +- **Description:** The unique identifier of the SemanticModel to be updated. +- **Type:** String +- **Mandatory:** Yes + +### SemanticModelName + +- **Description:** The new name of the SemanticModel. +- **Type:** String +- **Mandatory:** Yes + +### SemanticModelDescription + +- **Description:** An optional new description for the SemanticModel. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a SemanticModel Name and Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$semanticModel = Get-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelName "SemanticModel-12345" +Update-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelId $semanticModel.id -SemanticModelName "Updated SemanticModel" -SemanticModelDescription "Updated description" +``` + +### Example 2: Update a SemanticModel Name Only + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$semanticModel = Get-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelName "SemanticModel-12345" +Update-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelId $semanticModel.id -SemanticModelName "UpdatedName" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SemanticModelId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: SemanticModel updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricSemanticModelDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricSemanticModelDefinition.md new file mode 100644 index 0000000..cbebfaa --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricSemanticModelDefinition.md @@ -0,0 +1,69 @@ +# Update-FabricSemanticModelDefinition + +## Overview + +Updates the definition of an existing SemanticModel in a Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. + +## Features + +- Sends a PATCH request to update the content or metadata of a specified SemanticModel. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding SemanticModel content as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SemanticModel exists. +- **Type:** String +- **Mandatory:** Yes + +### SemanticModelId + +- **Description:** The unique identifier of the SemanticModel to be updated. +- **Type:** String +- **Mandatory:** Yes + +### SemanticModelPathDefinition + +- **Description:** The required path to the folder containing all files for the SemanticModel definition to be uploaded. +- **Type:** String +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Update SemanticModel Definition with a new JSON file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$semanticModel = Get-FabricSemanticModel -WorkspaceId $workspace.id -SemanticModelName "SemanticModel-67890" +Update-FabricSemanticModelDefinition -WorkspaceId $workspace.id -SemanticModelId $semanticModel.id -SemanticModelPathDefinition "C:\temp\API\SemanticModel\Updated" + +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SemanticModelId`. +3. Sends a PATCH request to the Microsoft Fabric API with the encoded SemanticModel content. +4. Handles API responses: + - `200`: SemanticModel definition updated successfully. + - `202`: SemanticModel definition update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricSparkCustomPool.md b/powershell/FabricACEToolkit/docs/Update-FabricSparkCustomPool.md new file mode 100644 index 0000000..ca42c12 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricSparkCustomPool.md @@ -0,0 +1,120 @@ +# Update-FabricSparkCustomPool + +## Overview + +The `Update-FabricSparkCustomPool` function updates an existing Spark custom pool in a specified Microsoft Fabric workspace. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Spark custom pool exists. +- **Type:** String +- **Mandatory:** Yes + +### SparkCustomPoolId + +- **Description:** The unique identifier of the Spark custom pool to be updated. +- **Type:** String +- **Mandatory:** Yes + +### InstancePoolName + +- **Description:** The new name of the Spark custom pool. +- **Type:** String +- **Mandatory:** Yes + +### NodeFamily + +- **Description:** The family of nodes to be used in the Spark custom pool. This must be 'MemoryOptimized'. +- **Type:** String +- **Mandatory:** Yes + +### NodeSize + +- **Description:** The size of the nodes to be used in the Spark custom pool. Options include 'Large', 'Medium', 'Small', 'XLarge', 'XXLarge'. +- **Type:** String +- **Mandatory:** Yes + +### AutoScaleEnabled + +- **Description:** Specifies whether auto-scaling is enabled for the Spark custom pool. +- **Type:** Boolean +- **Mandatory:** Yes + +### AutoScaleMinNodeCount + +- **Description:** The minimum number of nodes for auto-scaling in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### AutoScaleMaxNodeCount + +- **Description:** The maximum number of nodes for auto-scaling in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### DynamicExecutorAllocationEnabled + +- **Description:** Specifies whether dynamic executor allocation is enabled for the Spark custom pool. +- **Type:** Boolean +- **Mandatory:** Yes + +### DynamicExecutorAllocationMinExecutors + +- **Description:** The minimum number of executors for dynamic executor allocation in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### DynamicExecutorAllocationMaxExecutors + +- **Description:** The maximum number of executors for dynamic executor allocation in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Update a Spark custom pool with full configuration + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$spark = Get-FabricSparkCustomPool -WorkspaceId $workspace.id -SparkCustomPoolName "MyCustomPool" +Update-FabricSparkCustomPool ` +-WorkspaceId $workspace.id ` +-SparkCustomPoolId $spark.id ` +-InstancePoolName "MyPool2Updated" ` +-NodeFamily MemoryOptimized ` +-NodeSize Medium ` +-AutoScaleEnabled $true ` +-AutoScaleMinNodeCount 1 ` +-AutoScaleMaxNodeCount 2 ` +-DynamicExecutorAllocationEnabled $true ` +-DynamicExecutorAllocationMinExecutors 1 ` +-DynamicExecutorAllocationMaxExecutors 1 +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SparkCustomPoolId`. +3. Constructs the JSON request body with all the necessary configurations. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: Spark custom pool updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** diff --git a/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinition.md new file mode 100644 index 0000000..2ca1969 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinition.md @@ -0,0 +1,67 @@ +# Update-FabricSparkJobDefinition + +## Overview + +The `Update-FabricSparkJobDefinition` function updates an existing SparkJobDefinition in a specified Microsoft Fabric workspace. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SparkJobDefinition exists. +- **Type:** String +- **Mandatory:** No + +### SparkJobDefinitionId + +- **Description:** The unique identifier of the SparkJobDefinition to be updated. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionName + +- **Description:** The new name of the SparkJobDefinition. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionDescription + +- **Description:** An optional new description for the SparkJobDefinition. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a SparkJobDefinition Name and Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$sparkJobDefinition = Get-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionName "SparkJobDefinition02" +Update-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionId $sparkJobDefinition.id -SparkJobDefinitionName "SparkJobDefinition02 Updated" -SparkJobDefinitionDescription "Spark Job Definition Updated" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SparkJobDefinitionId`. +3. Constructs the JSON request body with optional description. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: SparkJobDefinition updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinitionDefinition.md b/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinitionDefinition.md new file mode 100644 index 0000000..1a4c240 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinitionDefinition.md @@ -0,0 +1,77 @@ +# Update-FabricSparkJobDefinitionDefinition + +## Overview + +Updates the definition of an existing SparkJobDefinition in a specified Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. + +## Features + +- Sends a PATCH request to update the content or metadata of a specified SparkJobDefinition. +- Validates token expiration before making the API request. +- Handles API responses with detailed error logging. +- Supports encoding SparkJobDefinition and platform-specific definition as Base64. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the SparkJobDefinition exists. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionId + +- **Description:** The unique identifier of the SparkJobDefinition to be updated. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionPathDefinition + +- **Description:** The required path to the SparkJobDefinition definition file to upload. +- **Type:** String +- **Mandatory:** Yes + +### SparkJobDefinitionPathPlatformDefinition + +- **Description:** An optional path to the platform-specific definition file to upload. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update SparkJobDefinition Definition with a new JSON file + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$sparkJobDefinition = Get-FabricSparkJobDefinition -WorkspaceId $workspace.id -SparkJobDefinitionName "SparkJobDefinition01" +Update-FabricSparkJobDefinitionDefinition ` +-WorkspaceId $workspace.id ` +-SparkJobDefinitionId $sparkJobDefinition.id ` +-SparkJobDefinitionPathDefinition "C:\temp\API\SparkJobDefinition\Definition.json" +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SparkJobDefinitionId`. +3. Sends a PATCH request to the Microsoft Fabric API with the encoded SparkJobDefinition content. +4. Handles API responses: + - `200`: SparkJobDefinition definition updated successfully. + - `202`: SparkJobDefinition definition update accepted, but operation is in progress. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricSparkSettings.md b/powershell/FabricACEToolkit/docs/Update-FabricSparkSettings.md new file mode 100644 index 0000000..31a069f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricSparkSettings.md @@ -0,0 +1,107 @@ +# Update-FabricSparkSettings + +## Overview + +The `Update-FabricSparkSettings` function updates an existing Spark custom pool in a specified Microsoft Fabric workspace. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the Spark custom pool exists. +- **Type:** String +- **Mandatory:** Yes + +### SparkSettingsId + +- **Description:** The unique identifier of the Spark custom pool to be updated. +- **Type:** String +- **Mandatory:** Yes + +### InstancePoolName + +- **Description:** The new name of the Spark custom pool. +- **Type:** String +- **Mandatory:** Yes + +### NodeFamily + +- **Description:** The family of nodes to be used in the Spark custom pool. This must be 'MemoryOptimized'. +- **Type:** String +- **Mandatory:** Yes + +### NodeSize + +- **Description:** The size of the nodes to be used in the Spark custom pool. Options include 'Large', 'Medium', 'Small', 'XLarge', 'XXLarge'. +- **Type:** String +- **Mandatory:** Yes + +### AutoScaleEnabled + +- **Description:** Specifies whether auto-scaling is enabled for the Spark custom pool. +- **Type:** Boolean +- **Mandatory:** Yes + +### AutoScaleMinNodeCount + +- **Description:** The minimum number of nodes for auto-scaling in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### AutoScaleMaxNodeCount + +- **Description:** The maximum number of nodes for auto-scaling in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### DynamicExecutorAllocationEnabled + +- **Description:** Specifies whether dynamic executor allocation is enabled for the Spark custom pool. +- **Type:** Boolean +- **Mandatory:** Yes + +### DynamicExecutorAllocationMinExecutors + +- **Description:** The minimum number of executors for dynamic executor allocation in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +### DynamicExecutorAllocationMaxExecutors + +- **Description:** The maximum number of executors for dynamic executor allocation in the Spark custom pool. +- **Type:** Integer +- **Mandatory:** Yes + +## Usage Examples + +### Example 1: Update a Spark custom pool with full configuration + +```powershell +Update-FabricSparkSettings -WorkspaceId "workspace-12345" -SparkSettingsId "pool-67890" -InstancePoolName "Updated Spark Pool" -NodeFamily "MemoryOptimized" -NodeSize "Large" -AutoScaleEnabled $true -AutoScaleMinNodeCount 1 -AutoScaleMaxNodeCount 10 -DynamicExecutorAllocationEnabled $true -DynamicExecutorAllocationMinExecutors 1 -DynamicExecutorAllocationMaxExecutors 10 +``` + +## Prerequisites + +- The global `$FabricConfig` configuration variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow + +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `SparkSettingsId`. +3. Constructs the JSON request body with all the necessary configurations. +4. Sends a PATCH request to the Microsoft Fabric API. +5. Handles API responses: + - `200`: Spark custom pool updated successfully. + - Other codes: Logs and throws errors for unexpected responses. + +## Error Handling + +- Logs detailed error messages for invalid inputs or API failures. +- Provides robust error logging to assist in debugging issues. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricWarehouse.md b/powershell/FabricACEToolkit/docs/Update-FabricWarehouse.md new file mode 100644 index 0000000..4aa286f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricWarehouse.md @@ -0,0 +1,72 @@ +# Update-FabricWarehouse + +## Overview + +The `Update-FabricWarehouse` function updates an existing warehouse in a specified Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. It allows modifications to the warehouse's name and description. + +## Features + +- Validates the token using `Test-TokenExpired` before making the API request. +- Allows updates to the warehouse's name (mandatory) and description (optional). +- Provides detailed logging for debugging and error handling. + +## Parameters + +### WorkspaceId + +- **Description:** The unique identifier of the workspace where the warehouse exists. +- **Type:** String +- **Mandatory:** Yes + +### WarehouseId + +- **Description:** The unique identifier of the warehouse to be updated. +- **Type:** String +- **Mandatory:** Yes + +### WarehouseName + +- **Description:** The new name of the warehouse. +- **Type:** String +- **Mandatory:** Yes +- **Validation:** Only allows alphanumeric characters, spaces, and underscores. + +### WarehouseDescription + +- **Description:** An optional new description for the warehouse. +- **Type:** String +- **Mandatory:** No + +## Usage Examples + +### Example 1: Update a Warehouse + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$warehouse = Get-FabricWarehouse -WorkspaceId $workspace.id -WarehouseName "warehouse-67890" +Update-FabricWarehouse -WorkspaceId $workspace.id -WarehouseId $warehouse.id -WarehouseName "warehouse-67890 Updated" -WarehouseDescription "Warehouse Updated" +``` + +## Prerequisites + +- The global `$FabricConfig` variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be implemented to validate token expiry. + +## Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL based on `WorkspaceId` and `WarehouseId`. +3. Builds the request body in JSON format, including mandatory and optional parameters. +4. Sends a PATCH request to the API endpoint with the constructed JSON body. +5. Handles API responses and logs messages for debugging or error handling. + +## Error Handling + +- Logs detailed error messages for invalid inputs or failed API requests. +- Returns `null` if the API response code is not `200`. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricWorkspace.md b/powershell/FabricACEToolkit/docs/Update-FabricWorkspace.md new file mode 100644 index 0000000..f4d107d --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricWorkspace.md @@ -0,0 +1,69 @@ +# Update-FabricWorkspace + +## Overview + +The `Update-FabricWorkspace` function updates an existing workspace in a specified Microsoft Fabric by sending a PATCH request to the Microsoft Fabric API. It allows modifications to the workspace's name and description. + +## Features + +- Validates the token using `Test-TokenExpired` before making the API request. +- Allows updates to the workspace's name (mandatory) and description (optional). +- Provides detailed logging for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace to be updated. +- **Type:** String + +### WorkspaceName *(Mandatory)* + +- **Description:** The new name for the workspace. +- **Type:** String +- **Validation:** Only allows alphanumeric characters, spaces, and underscores. + +### WorkspaceDescription *(Optional)* + +- **Description:** The new description for the workspace. +- **Type:** String + +## Usage Examples + +### Example 1: Update a Workspace Name + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Update-FabricWorkspace -WorkspaceId $workspace.id -WorkspaceName "workspace-12345 UPDATED" +``` + +### Example 2: Update a Workspace Name and Description + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Update-FabricWorkspace -WorkspaceId $workspace.id -WorkspaceName "workspace-12345 UPDATED" -WorkspaceDescription "Updated description" +``` + +## Prerequisites + +- The global `$FabricConfig` variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be implemented to validate token expiry. + +## Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL based on `WorkspaceId`. +3. Builds the request body in JSON format, including mandatory and optional parameters. +4. Sends a PATCH request to the API endpoint with the constructed JSON body. +5. Handles API responses and logs messages for debugging or error handling. + +## Error Handling + +- Logs detailed error messages for invalid inputs or failed API requests. +- Returns `null` if the API response code is not `200`. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Update-FabricWorkspaceRoleAssignment.md b/powershell/FabricACEToolkit/docs/Update-FabricWorkspaceRoleAssignment.md new file mode 100644 index 0000000..87c5a68 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Update-FabricWorkspaceRoleAssignment.md @@ -0,0 +1,69 @@ +# Update-FabricWorkspaceRoleAssignment + +## Overview + +The `Update-FabricWorkspaceRoleAssignment` function updates the role assigned to a principal in a specified Microsoft Fabric workspace by sending a PATCH request to the Microsoft Fabric API. + +## Features + +- Validates the token using `Test-TokenExpired` before making the API request. +- Allows updates to the role of a principal in the workspace. +- Provides detailed logging for debugging and error handling. + +## Parameters + +### WorkspaceId *(Mandatory)* + +- **Description:** The unique identifier of the workspace where the role assignment exists. +- **Type:** String + +### WorkspaceRoleAssignmentId *(Mandatory)* + +- **Description:** The unique identifier of the role assignment to be updated. +- **Type:** String + +### WorkspaceRole *(Mandatory)* + +- **Description:** The new role to assign to the principal. Must be one of the following: + - Admin + - Contributor + - Member + - Viewer +- **Type:** String + +## Usage Examples + +### Example 1: Update a Role Assignment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +Get-FabricWorkspaceRoleAssignment -WorkspaceId $workspace.id +Update-FabricWorkspaceRoleAssignment ` +-WorkspaceId $workspace.id ` +-WorkspaceRoleAssignmentId "999999999-9999-9999-9999-9999999999" ` +-WorkspaceRole Contributor +``` + +## Prerequisites + +- The global `$FabricConfig` variable must include: + - `BaseUrl`: The base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- The `Test-TokenExpired` function must be implemented to validate token expiry. + +## Workflow + +1. Validates the token using `Test-TokenExpired`. +2. Constructs the API URL based on `WorkspaceId` and `WorkspaceRoleAssignmentId`. +3. Builds the request body in JSON format with the `WorkspaceRole`. +4. Sends a PATCH request to the API endpoint with the constructed JSON body. +5. Handles API responses and logs messages for debugging or error handling. + +## Error Handling + +- Logs detailed error messages for invalid inputs or failed API requests. +- Returns `null` if the API response code is not `200`. + +## Author + +**Tiago Balabuch** \ No newline at end of file diff --git a/powershell/FabricACEToolkit/docs/Upload-FabricEnvironmentStagingLibrary.md b/powershell/FabricACEToolkit/docs/Upload-FabricEnvironmentStagingLibrary.md new file mode 100644 index 0000000..5773e1f --- /dev/null +++ b/powershell/FabricACEToolkit/docs/Upload-FabricEnvironmentStagingLibrary.md @@ -0,0 +1,50 @@ +# Upload-FabricEnvironmentStagingLibrary + +## Overview +The `Upload-FabricEnvironmentStagingLibrary` function sends a POST request to the Microsoft Fabric API to upload a library to the specified environment staging area for the given workspace. + +## Features +- Validates token expiration before making the API request. +- Constructs and sends a POST request to upload a library. +- Handles successful and error responses. + +## Parameters + +### WorkspaceId +- **Description:** The unique identifier of the workspace where the environment exists. +- **Type:** String +- **Mandatory:** Yes + +### EnvironmentId +- **Description:** The unique identifier of the environment where the library will be uploaded. +- **Type:** String +- **Mandatory:** Yes + +### Example 1: Cancels the publish operation for a specified environment + +```powershell +$workspace = Get-FabricWorkspace -WorkspaceName "workspace-12345" +$env = Get-FabricEnvironment -WorkspaceId $workspace.id -EnvironmentName "Env02" +Upload-FabricEnvironmentStagingLibrary -WorkspaceId $workspace.id -EnvironmentId $env.id +``` + +## Prerequisites +- Use the command `Set-FabricApiHeaders` to set global configuration variable `$FabricConfig`, containing: + - `BaseUrl`: Base API endpoint for Fabric. + - `FabricHeaders`: Authentication headers for API requests. +- Token validation requires the `Test-TokenExpired` helper function. + +## Key Workflow +1. Validates the authentication token using `Test-TokenExpired`. +2. Constructs the API URL using `BaseUrl`, `WorkspaceId`, and `EnvironmentId`. +3. Constructs the request body for the library upload. +4. Sends a POST request to upload the library. +5. Validates the API response and handles results accordingly. + +## Error Handling +- Logs descriptive error messages if API requests fail or invalid input is detected. +- Returns `null` for any errors encountered during execution. + +## Author +**Tiago Balabuch** + diff --git a/powershell/FabricACEToolkit/docs/index.md b/powershell/FabricACEToolkit/docs/index.md new file mode 100644 index 0000000..50e31e8 --- /dev/null +++ b/powershell/FabricACEToolkit/docs/index.md @@ -0,0 +1,248 @@ +# Fabric ACE Toolkit Documentation + +## Overview + +The FabricACEToolkit is a collection of PowerShell scripts designed to interact with the Microsoft Fabric API. It provides functionalities to manage various resources within a Microsoft Fabric workspace, such as Spark Job Definitions, ML Models, Reports, Notebooks, and more. + +## Table of Contents + +- [Installation](#installation) +- [Configuration](#configuration) +- [Functions](#functions) +- [Examples](#examples) +- [License](#license) + +## Installation + + +To install the FabricACEToolkit, clone the repository and import the module in your PowerShell session: + +```bash +git clone https://github.com/tiagobalabuch/FabricACEToolkit.git +Import-Module ./FabricACEToolkit/FabricACEToolkit.psm1 +``` + +## Configuration + +Before using the toolkit, set the Fabric Headers using the command `Set-FabricApiHeaders`. Without this you cannot call an API global variable with your API `BaseUrl` and `FabricHeaders`: + +```powershell +Set-FabricApiHeaders -tenantId "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" +``` + +## Functions + +## Public Functions + +### Capacity +- [Get-FabricCapacity.ps1](Get-FabricCapacity.md) + +### Dashboard +- [Get-FabricDashboard.ps1](Get-FabricDashboard.md) + +### Data Pipeline +- [Get-FabricDataPipeline.ps1](Get-FabricDataPipeline.md) +- [New-FabricDataPipeline.ps1](New-FabricDataPipeline.md) +- [Remove-FabricDataPipelines.ps1](Remove-FabricDataPipeline.md) +- [Update-FabricNotebook.ps1](Update-FabricDataPipeline.md) +### Datamart +- [Get-FabricDatamart.ps1](Get-FabricDatamart.md) + +### Domain +- [Assign-FabricDomainWorkspaceByCapacity.ps1](Assign-FabricDomainWorkspaceByCapacity.md) +- [Assign-FabricDomainWorkspaceById.ps1](Assign-FabricDomainWorkspaceById.md) +- [Assign-FabricDomainWorkspaceByPrincipal.ps1](Assign-FabricDomainWorkspaceByPrincipal.md) +- [Assign-FabricDomainWorkspaceRoleAssignment.ps1](Assign-FabricDomainWorkspaceRoleAssignment.md) +- [Get-FabricDomain.ps1](Get-FabricDomain.md) +- [Get-FabricDomainWorkspace.ps1](Get-FabricDomainWorkspace.md) +- [New-FabricDomain.ps1](New-FabricDomain.md) +- [Remove-FabricDomain.ps1](Remove-FabricDomain.md) +- [Unassign-FabricDomainWorkspace.ps1](Unassign-FabricDomainWorkspace.md) +- [Unassign-FabricDomainWorkspaceRoleAssignment.ps1](Unassign-FabricDomainWorkspaceRoleAssignment.md) +- [Update-FabricDomain.ps1](Update-FabricDomain.md) + +### Environment +- [Get-FabricEnvironment.ps1](Get-FabricEnvironment.md) +- [Get-FabricEnvironmentLibrary.ps1](Get-FabricEnvironmentLibrary.md) +- [Get-FabricEnvironmentSparkCompute.ps1](Get-FabricEnvironmentSparkCompute.md) +- [Get-FabricEnvironmentStagingLibrary.ps1](Get-FabricEnvironmentStagingLibrary.md) +- [Get-FabricEnvironmentStagingSparkCompute.ps1](Get-FabricEnvironmentStagingSparkCompute.md) +- [New-FabricEnvironment.ps1](New-FabricEnvironment.md) +- [Publish-FabricEnvironment.ps1](Publish-FabricEnvironment.md) +- [Remove-FabricEnvironment.ps1](Remove-FabricEnvironment.md) +- [Remove-FabricEnvironmentStagingLibrary.ps1](Remove-FabricEnvironmentStagingLibrary.md) +- [Stop-FabricEnvironmentPublish.ps1](Stop-FabricEnvironmentPublish.md) +- [Update-FabricEnvironment.ps1](Update-FabricEnvironment.md) +- [Update-FabricEnvironmentStagingSparkCompute.ps1](Update-FabricEnvironmentStagingSparkCompute.md) +- [Upload-FabricEnvironmentStagingLibrary.ps1](Upload-FabricEnvironmentStagingLibrary.md) + +### Eventhouse +- [Get-FabricEventhouse.ps1](Get-FabricEventhouse.md) +- [Get-FabricEventhouseDefinition.ps1](Get-FabricEventhouseDefinition.md) +- [New-FabricEventhouse.ps1](New-FabricEventhouse.md) +- [Remove-FabricEventhouse.ps1](Remove-FabricEventhouse.md) +- [Update-FabricEventhouse.ps1](Update-FabricEventhouse.md) +- [Update-FabricEventhouseDefinition.ps1](Update-FabricEventhouseDefinition.md) + +### Eventstream +- [Get-FabricEventstream.ps1](Get-FabricEventstream.md) +- [Get-FabricEventstreamDefinition.ps1](Get-FabricEventstreamDefinition.md) +- [New-FabricEventstream.ps1](New-FabricEventstream.md) +- [Remove-FabricEventstream.ps1](Remove-FabricEventstream.md) +- [Update-FabricEventstream.ps1](Update-FabricEventstream.md) +- [Update-FabricEventstreamDefinition.ps1](Update-FabricEventstreamDefinition.md) + +### KQL Dashboard +- [Get-FabricKQLDashboard.ps1](Get-FabricKQLDashboard.md) +- [Get-FabricKQLDashboardDefinition.ps1](Get-FabricKQLDashboardDefinition.md) +- [New-FabricKQLDashboard.ps1](New-FabricKQLDashboard.md) +- [Remove-FabricKQLDashboard.ps1](Remove-FabricKQLDashboard.md) +- [Update-FabricKQLDashboard.ps1](Update-FabricKQLDashboard.md) +- [Update-FabricKQLDashboardDefinition.ps1](Update-FabricKQLDashboardDefinition.md) + +### KQL Database +- [Get-FabricKQLDatabase.ps1](Get-FabricKQLDatabase.md) +- [Get-FabricKQLDatabaseDefinition.ps1](Get-FabricKQLDatabaseDefinition.md) +- [New-FabricKQLDatabase.ps1](New-FabricKQLDatabase.md) +- [Remove-FabricKQLDatabase.ps1](Remove-FabricKQLDatabase.md) +- [Update-FabricKQLDatabase.ps1](Update-FabricKQLDatabase.md) +- [Update-FabricKQLDatabaseDefinition.ps1](Update-FabricKQLDatabaseDefinition.md) + +### KQL Queryset +- [Get-FabricKQLQueryset.ps1](Get-FabricKQLQueryset.md) +- [Get-FabricKQLQuerysetDefinition.ps1](Get-FabricKQLQuerysetDefinition.md) +- [New-FabricKQLQueryset.ps1](New-FabricKQLQueryset.md) +- [Remove-FabricKQLQueryset.ps1](Remove-FabricKQLQueryset.md) +- [Update-FabricKQLQueryset.ps1](Update-FabricKQLQueryset.md) +- [Update-FabricKQLQuerysetDefinition.ps1](Update-FabricKQLQuerysetDefinition.md) + +### Lakehouse +- [Get-FabricLakehouse.ps1](Get-FabricLakehouse.md) +- [Get-FabricLakehouseTable.ps1](Get-FabricLakehouseTable.md) +- [Load-FabricLakehouseTable.ps1](Load-FabricLakehouseTable.md) +- [New-FabricLakehouse.ps1](New-FabricLakehouse.md) +- [Remove-FabricLakehouse.ps1](Remove-FabricLakehouse.md) +- [Start-FabricLakehouseTableMaintenance.ps1](Start-FabricLakehouseTableMaintenance.md) +- [Update-FabricLakehouse.ps1](Update-FabricLakehouse.md) + + +### Mirrored Database +- [Get-FabricMirroredDatabase.ps1](Get-FabricMirroredDatabase.md) +- [Get-FabricMirroredDatabaseDefinition.ps1](Get-FabricMirroredDatabaseDefinition.md) +- [Get-FabricMirroredDatabaseStatus.ps1](Get-FabricMirroredDatabaseStatus.md) +- [Get-FabricMirroredDatabaseTableStatus.ps1](Get-FabricMirroredDatabaseTableStatus.md) +- [New-FabricMirroredDatabase.ps1](New-FabricMirroredDatabase.md) +- [Remove-FabricMirroredDatabase.ps1](Remove-FabricMirroredDatabase.md) +- [Start-FabricMirroredDatabaseMirroring.ps1](Start-FabricMirroredDatabaseMirroring.md) +- [Stop-FabricMirroredDatabaseMirroring.ps1](Stop-FabricMirroredDatabaseMirroring.md) +- [Update-FabricMirroredDatabase.ps1](Update-FabricMirroredDatabase.md) +- [Update-FabricMirroredDatabaseDefinition.ps1](Update-FabricMirroredDatabaseDefinition.md) + + +### Mirrored Warehouse + +[Get-FabricMirroredWarehouse.ps1](Get-FabricMirroredWarehouse.md) + +### ML Experiment +- [Get-FabricMLExperiment.ps1](Get-FabricMLExperiment.md) +- [New-FabricMLExperiment.ps1](New-FabricMLExperiment.md) +- [Remove-FabricMLExperiment.ps1](Remove-FabricMLExperiment.md) +- [Update-FabricMLExperiment.ps1](Update-FabricMLExperiment.md) + +### ML Model +- [Get-FabricMLModel.ps1](Get-FabricMLModel.md) +- [New-FabricMLModel.ps1](New-FabricMLModel.md) +- [Remove-FabricMLModel.ps1](Remove-FabricMLModel.md) +- [Update-FabricMLModel.ps1](Update-FabricMLModel.md) + +### Notebook +- [Get-FabricNotebook.ps1](Get-FabricNotebook.md) +- [Get-FabricNotebookDefinition.ps1](Get-FabricNotebookDefinition.md) +- [New-FabricNotebook.ps1](New-FabricNotebook.md) +- [Remove-FabricNotebook.ps1](Remove-FabricNotebook.md) +- [Update-FabricNotebook.ps1](Update-FabricNotebook.md) +- [Update-FabricNotebookDefinition.ps1](Update-FabricNotebookDefinition.md) + +### Paginated Reports +- [Get-FabricPaginatedReport.ps1](Get-FabricPaginatedReport.md) +- [Update-FabricPaginatedReport.ps1](Update-FabricPaginatedReport.md) + +### Reflex +- [Get-FabricReflex.ps1](Get-FabricReflex.md) +- [Get-FabricReflexDefinition.ps1](Get-FabricReflexDefinition.md) +- [New-FabricReflex.ps1](New-FabricReflex.md) +- [Remove-FabricReflex.ps1](Remove-FabricReflex.md) +- [Update-FabricReflex.ps1](Update-FabricReflex.md) +- [Update-FabricReflexDefinition.ps1](Update-FabricReflexDefinition.md) + +### Report +- [Get-FabricReport.ps1](Get-FabricReport.md) +- [Get-FabricReportDefinition.ps1](Get-FabricReportDefinition.md) +- [New-FabricReport.ps1](New-FabricReport.md) +- [Remove-FabricReport.ps1](Remove-FabricReport.md) +- [Update-FabricReport.ps1](Update-FabricReport.md) +- [Update-FabricReportDefinition.ps1](Update-FabricReportDefinition.md) + +### Semantic Model +- [Get-FabricSemanticModel.ps1](Get-FabricSemanticModel.md) +- [Get-FabricSemanticModelDefinition.ps1](Get-FabricSemanticModelDefinition.md) +- [New-FabricSemanticModel.ps1](New-FabricSemanticModel.md) +- [Remove-FabricSemanticModel.ps1](Remove-FabricSemanticModel.md) +- [Update-FabricSemanticModel.ps1](Update-FabricSemanticModel.md) +- [Update-FabricSemanticModelDefinition.ps1](Update-FabricSemanticModelDefinition.md) + +### Spark +- [Get-FabricSparkCustomPool.ps1](Get-FabricSparkCustomPool.md) +- [Get-FabricSparkSettings.ps1](Get-FabricSparkSettings.md) +- [New-FabricSparkCustomPool.ps1](New-FabricSparkCustomPool.md) +- [Remove-FabricSparkCustomPool.ps1](Remove-FabricSparkCustomPool.md) +- [Update-FabricSparkCustomPool.ps1](Update-FabricSparkCustomPool.md) +- [Update-FabricSparkSettings.ps1](Update-FabricSparkSettings.md) + +### Spark Job Definition +- [Get-FabricSparkJobDefinition.ps1](Get-FabricSparkJobDefinition.md) +- [Get-FabricSparkJobDefinitionDefinition.ps1](Get-FabricSparkJobDefinitionDefinition.md) +- [New-FabricSparkJobDefinition.ps1](New-FabricSparkJobDefinition.md) +- [Remove-FabricSparkJobDefinition.ps1](Remove-FabricSparkJobDefinition.md) +- [Start-FabricSparkJobDefinitionOnDemand.ps1](Start-FabricSparkJobDefinitionOnDemand.md) +- [Update-FabricSparkJobDefinition.ps1](Update-FabricSparkJobDefinition.md) +- [Update-FabricSparkJobDefinitionDefinition.ps1](Update-FabricSparkJobDefinitionDefinition.md) + +### SQL Endpoints +- [Get-FabricSQLEndpoint.ps1](Get-FabricSQLEndpoint.md) + +### Tenant +- [Get-FabricTenantSetting.ps1](Get-FabricTenantSetting.md) +- [Get-FabricTenantSettingOverridesCapacity.ps1](Get-FabricTenantSettingOverridesCapacity.md) + +## Utils +- [Convert-FromBase64.ps1](Convert-FromBase64.md) +- [Convert-ToBase64.ps1](Convert-ToBase64.md) +- [Get-FabricLongRunningOperation.ps1](Get-FabricLongRunningOperation.md) +- [Get-FabricLongRunningOperationResult.ps1](Get-FabricLongRunningOperationResult.md) +- [Set-FabricApiHeaders.ps1](Set-FabricApiHeaders.md) + +### Warehouse +- [Get-FabricWarehouse.ps1](Get-FabricWarehouse.md) +- [New-FabricWarehouse.ps1](New-FabricWarehouse.md) +- [Remove-FabricWarehouse.ps1](Remove-FabricWarehouse.md) +- [Update-FabricWarehouse.ps1](Update-FabricWarehouse.md) + +### Workspace +- [Add-FabricWorkspaceIdentity.ps1](Add-FabricWorkspaceIdentity.md) +- [Add-FabricWorkspaceRoleAssignment.ps1](Add-FabricWorkspaceRoleAssignments.md) +- [Assign-FabricWorkspaceCapacity.ps1](Assign-FabricWorkspaceCapacity.md) +- [Get-FabricWorkspace.ps1](Get-FabricWorkspace.md) +- [Get-FabricWorkspaceRoleAssignment.ps1](Get-FabricWorkspaceRoleAssignment.md) +- [New-FabricWorkspace.ps1](New-FabricWorkspace.md) +- [Remove-FabricWorkspace.ps1](Remove-FabricWorkspace.md) +- [Remove-FabricWorkspaceIdentity.ps1](Remove-FabricWorkspaceIdentity.md) +- [Remove-FabricWorkspaceRoleAssignment.ps1](Remove-FabricWorkspaceRoleAssignment.md) +- [Unassign-FabricWorkspaceCapacity.ps1](Unassign-FabricWorkspaceCapacity.md) +- [Update-FabricWorkspace.ps1](Update-FabricWorkspace.md) +- [Update-FabricWorkspaceRoleAssignment.ps1](Update-FabricWorkspaceRoleAssignment.md) + + + +## License +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. \ No newline at end of file diff --git a/powershell/README.md b/powershell/README.md new file mode 100644 index 0000000..a6d00bf --- /dev/null +++ b/powershell/README.md @@ -0,0 +1,273 @@ +# Powershell FabricACEToolkit + +## Overview +The FabricACEToolkit is a collection of PowerShell scripts designed to interact with the Microsoft Fabric API. It provides functionalities to manage various resources within a Microsoft Fabric workspace, such as Spark Job Definitions, ML Models, Reports, Notebooks, and more. + +## Table of Contents +- [Installation](#installation) +- [Prerequisites](#prerequisites) +- [Configuration](#configuration) +- [Functions](#functions) +- [License](#license) + +## Installation +To install the FabricACEToolkit, clone the repository and import the module in your PowerShell session: +```sh +git clone https://github.com/microsoft/fabric-toolbox.git +Import-Module ./fabric-toolbox/powershell/FabricACEToolkit.psm1 +``` + +## Prerequisites + +You can install the entire Azure PowerShell module or just the Az.Accounts module, which is required for this toolkit. + +1. [Instal Azure PowerShell module](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell?view=azps-13.0.0) +2. [Install individual module](https://learn.microsoft.com/en-us/powershell/azure/install-azps-optimized?view=azps-13.0.0#install-individual-service-specific-modules) + + +```powershell +Install-Module -Name Az -Repository PSGallery -Force +``` +```powershell +Install-Module -Name Az.Accounts -Force -AllowClobber +``` + +> [!NOTE] +> After install or update you can import the Az.Accounts module + +```powershell +Import-Module Az.Accounts -Force +``` + +## Configuration + +Before using the toolkit, set the Fabric Headers using the command `Set-FabricApiHeaders`. Without this you cannot call an API global variable with your API `BaseUrl` and `FabricHeaders`: + +```powershell +# User Principal +Set-FabricApiHeaders -tenantId "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" +``` + +```powershell +# Service Principal +$tenantId = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" +$appId = "00000000-0000-0000-0000-000000000000" +$appSecret = "your-secret" +$secureAppSecret = $appSecret | ConvertTo-SecureString -AsPlainText -Force + +Set-FabricApiHeadersV2 -TenantId $tenantId -AppId $appId -AppSecret $secureAppSecret + +``` + +## Functions + +### Capacity +- [Get-FabricCapacity.ps1](/powershell/FabricACEToolkit/docs/Get-FabricCapacity.md) + +### Dashboard +- [Get-FabricDashboard.ps1](/powershell/FabricACEToolkit/docs/Get-FabricDashboard.md) + +### Data Pipeline +- [Get-FabricDataPipeline.ps1](/powershell/FabricACEToolkit/docs/Get-FabricDataPipeline.md) +- [New-FabricDataPipeline.ps1](/powershell/FabricACEToolkit/docs/New-FabricDataPipeline.md) +- [Remove-FabricDataPipelines.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricDataPipeline.md) +- [Update-FabricNotebook.ps1](/powershell/FabricACEToolkit/docs/Update-FabricDataPipeline.md) +### Datamart +- [Get-FabricDatamart.ps1](/powershell/FabricACEToolkit/docs/Get-FabricDatamart.md) + +### Domain +- [Assign-FabricDomainWorkspaceByCapacity.ps1](/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByCapacity.md) +- [Assign-FabricDomainWorkspaceById.ps1](/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceById.md) +- [Assign-FabricDomainWorkspaceByPrincipal.ps1](/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceByPrincipal.md) +- [Assign-FabricDomainWorkspaceRoleAssignment.ps1](/powershell/FabricACEToolkit/docs/Assign-FabricDomainWorkspaceRoleAssignment.md) +- [Get-FabricDomain.ps1](/powershell/FabricACEToolkit/docs/Get-FabricDomain.md) +- [Get-FabricDomainWorkspace.ps1](/powershell/FabricACEToolkit/docs/Get-FabricDomainWorkspace.md) +- [New-FabricDomain.ps1](/powershell/FabricACEToolkit/docs/New-FabricDomain.md) +- [Remove-FabricDomain.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricDomain.md) +- [Unassign-FabricDomainWorkspace.ps1](/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspace.md) +- [Unassign-FabricDomainWorkspaceRoleAssignment.ps1](/powershell/FabricACEToolkit/docs/Unassign-FabricDomainWorkspaceRoleAssignment.md) +- [Update-FabricDomain.ps1](/powershell/FabricACEToolkit/docs/Update-FabricDomain.md) + +### Environment +- [Get-FabricEnvironment.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEnvironment.md) +- [Get-FabricEnvironmentLibrary.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentLibrary.md) +- [Get-FabricEnvironmentSparkCompute.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentSparkCompute.md) +- [Get-FabricEnvironmentStagingLibrary.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingLibrary.md) +- [Get-FabricEnvironmentStagingSparkCompute.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEnvironmentStagingSparkCompute.md) +- [New-FabricEnvironment.ps1](/powershell/FabricACEToolkit/docs/New-FabricEnvironment.md) +- [Publish-FabricEnvironment.ps1](/powershell/FabricACEToolkit/docs/Publish-FabricEnvironment.md) +- [Remove-FabricEnvironment.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricEnvironment.md) +- [Remove-FabricEnvironmentStagingLibrary.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricEnvironmentStagingLibrary.md) +- [Stop-FabricEnvironmentPublish.ps1](/powershell/FabricACEToolkit/docs/Stop-FabricEnvironmentPublish.md) +- [Update-FabricEnvironment.ps1](/powershell/FabricACEToolkit/docs/Update-FabricEnvironment.md) +- [Update-FabricEnvironmentStagingSparkCompute.ps1](/powershell/FabricACEToolkit/docs/Update-FabricEnvironmentStagingSparkCompute.md) +- [Upload-FabricEnvironmentStagingLibrary.ps1](/powershell/FabricACEToolkit/docs/Upload-FabricEnvironmentStagingLibrary.md) + +### Eventhouse +- [Get-FabricEventhouse.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEventhouse.md) +- [Get-FabricEventhouseDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEventhouseDefinition.md) +- [New-FabricEventhouse.ps1](/powershell/FabricACEToolkit/docs/New-FabricEventhouse.md) +- [Remove-FabricEventhouse.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricEventhouse.md) +- [Update-FabricEventhouse.ps1](/powershell/FabricACEToolkit/docs/Update-FabricEventhouse.md) +- [Update-FabricEventhouseDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricEventhouseDefinition.md) + +### Eventstream +- [Get-FabricEventstream.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEventstream.md) +- [Get-FabricEventstreamDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricEventstreamDefinition.md) +- [New-FabricEventstream.ps1](/powershell/FabricACEToolkit/docs/New-FabricEventstream.md) +- [Remove-FabricEventstream.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricEventstream.md) +- [Update-FabricEventstream.ps1](/powershell/FabricACEToolkit/docs/Update-FabricEventstream.md) +- [Update-FabricEventstreamDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricEventstreamDefinition.md) + +### KQL Dashboard +- [Get-FabricKQLDashboard.ps1](/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboard.md) +- [Get-FabricKQLDashboardDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricKQLDashboardDefinition.md) +- [New-FabricKQLDashboard.ps1](/powershell/FabricACEToolkit/docs/New-FabricKQLDashboard.md) +- [Remove-FabricKQLDashboard.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricKQLDashboard.md) +- [Update-FabricKQLDashboard.ps1](/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboard.md) +- [Update-FabricKQLDashboardDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricKQLDashboardDefinition.md) + +### KQL Database +- [Get-FabricKQLDatabase.ps1](/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabase.md) +- [Get-FabricKQLDatabaseDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricKQLDatabaseDefinition.md) +- [New-FabricKQLDatabase.ps1](/powershell/FabricACEToolkit/docs/New-FabricKQLDatabase.md) +- [Remove-FabricKQLDatabase.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricKQLDatabase.md) +- [Update-FabricKQLDatabase.ps1](/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabase.md) +- [Update-FabricKQLDatabaseDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricKQLDatabaseDefinition.md) + +### KQL Queryset +- [Get-FabricKQLQueryset.ps1](/powershell/FabricACEToolkit/docs/Get-FabricKQLQueryset.md) +- [Get-FabricKQLQuerysetDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricKQLQuerysetDefinition.md) +- [New-FabricKQLQueryset.ps1](/powershell/FabricACEToolkit/docs/New-FabricKQLQueryset.md) +- [Remove-FabricKQLQueryset.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricKQLQueryset.md) +- [Update-FabricKQLQueryset.ps1](/powershell/FabricACEToolkit/docs/Update-FabricKQLQueryset.md) +- [Update-FabricKQLQuerysetDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricKQLQuerysetDefinition.md) + +### Lakehouse +- [Get-FabricLakehouse.ps1](/powershell/FabricACEToolkit/docs/Get-FabricLakehouse.md) +- [Get-FabricLakehouseTable.ps1](/powershell/FabricACEToolkit/docs/Get-FabricLakehouseTable.md) +- [Load-FabricLakehouseTable.ps1](/powershell/FabricACEToolkit/docs/Load-FabricLakehouseTable.md) +- [New-FabricLakehouse.ps1](/powershell/FabricACEToolkit/docs/New-FabricLakehouse.md) +- [Remove-FabricLakehouse.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricLakehouse.md) +- [Start-FabricLakehouseTableMaintenance.ps1](/powershell/FabricACEToolkit/docs/Start-FabricLakehouseTableMaintenance.md) +- [Update-FabricLakehouse.ps1](/powershell/FabricACEToolkit/docs/Update-FabricLakehouse.md) + + +### Mirrored Database +- [Get-FabricMirroredDatabase.ps1](/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabase.md) +- [Get-FabricMirroredDatabaseDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseDefinition.md) +- [Get-FabricMirroredDatabaseStatus.ps1](/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseStatus.md) +- [Get-FabricMirroredDatabaseTableStatus.ps1](/powershell/FabricACEToolkit/docs/Get-FabricMirroredDatabaseTableStatus.md) +- [New-FabricMirroredDatabase.ps1](/powershell/FabricACEToolkit/docs/New-FabricMirroredDatabase.md) +- [Remove-FabricMirroredDatabase.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricMirroredDatabase.md) +- [Start-FabricMirroredDatabaseMirroring.ps1](/powershell/FabricACEToolkit/docs/Start-FabricMirroredDatabaseMirroring.md) +- [Stop-FabricMirroredDatabaseMirroring.ps1](/powershell/FabricACEToolkit/docs/Stop-FabricMirroredDatabaseMirroring.md) +- [Update-FabricMirroredDatabase.ps1](/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabase.md) +- [Update-FabricMirroredDatabaseDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricMirroredDatabaseDefinition.md) + + +### Mirrored Warehouse + +[Get-FabricMirroredWarehouse.ps1](/powershell/FabricACEToolkit/docs/Get-FabricMirroredWarehouse.md) + +### ML Experiment +- [Get-FabricMLExperiment.ps1](/powershell/FabricACEToolkit/docs/Get-FabricMLExperiment.md) +- [New-FabricMLExperiment.ps1](/powershell/FabricACEToolkit/docs/New-FabricMLExperiment.md) +- [Remove-FabricMLExperiment.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricMLExperiment.md) +- [Update-FabricMLExperiment.ps1](/powershell/FabricACEToolkit/docs/Update-FabricMLExperiment.md) + +### ML Model +- [Get-FabricMLModel.ps1](/powershell/FabricACEToolkit/docs/Get-FabricMLModel.md) +- [New-FabricMLModel.ps1](/powershell/FabricACEToolkit/docs/New-FabricMLModel.md) +- [Remove-FabricMLModel.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricMLModel.md) +- [Update-FabricMLModel.ps1](/powershell/FabricACEToolkit/docs/Update-FabricMLModel.md) + +### Notebook +- [Get-FabricNotebook.ps1](/powershell/FabricACEToolkit/docs/Get-FabricNotebook.md) +- [Get-FabricNotebookDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricNotebookDefinition.md) +- [New-FabricNotebook.ps1](/powershell/FabricACEToolkit/docs/New-FabricNotebook.md) +- [Remove-FabricNotebook.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricNotebook.md) +- [Update-FabricNotebook.ps1](/powershell/FabricACEToolkit/docs/Update-FabricNotebook.md) +- [Update-FabricNotebookDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricNotebookDefinition.md) + +### Paginated Reports +- [Get-FabricPaginatedReport.ps1](/powershell/FabricACEToolkit/docs/Get-FabricPaginatedReport.md) +- [Update-FabricPaginatedReport.ps1](/powershell/FabricACEToolkit/docs/Update-FabricPaginatedReport.md) + +### Reflex +- [Get-FabricReflex.ps1](/powershell/FabricACEToolkit/docs/Get-FabricReflex.md) +- [Get-FabricReflexDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricReflexDefinition.md) +- [New-FabricReflex.ps1](/powershell/FabricACEToolkit/docs/New-FabricReflex.md) +- [Remove-FabricReflex.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricReflex.md) +- [Update-FabricReflex.ps1](/powershell/FabricACEToolkit/docs/Update-FabricReflex.md) +- [Update-FabricReflexDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricReflexDefinition.md) + +### Report +- [Get-FabricReport.ps1](/powershell/FabricACEToolkit/docs/Get-FabricReport.md) +- [Get-FabricReportDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricReportDefinition.md) +- [New-FabricReport.ps1](/powershell/FabricACEToolkit/docs/New-FabricReport.md) +- [Remove-FabricReport.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricReport.md) +- [Update-FabricReport.ps1](/powershell/FabricACEToolkit/docs/Update-FabricReport.md) +- [Update-FabricReportDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricReportDefinition.md) + +### Semantic Model +- [Get-FabricSemanticModel.ps1](/powershell/FabricACEToolkit/docs/Get-FabricSemanticModel.md) +- [Get-FabricSemanticModelDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricSemanticModelDefinition.md) +- [New-FabricSemanticModel.ps1](/powershell/FabricACEToolkit/docs/New-FabricSemanticModel.md) +- [Remove-FabricSemanticModel.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricSemanticModel.md) +- [Update-FabricSemanticModel.ps1](/powershell/FabricACEToolkit/docs/Update-FabricSemanticModel.md) +- [Update-FabricSemanticModelDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricSemanticModelDefinition.md) + +### Spark +- [Get-FabricSparkCustomPool.ps1](/powershell/FabricACEToolkit/docs/Get-FabricSparkCustomPool.md) +- [Get-FabricSparkSettings.ps1](/powershell/FabricACEToolkit/docs/Get-FabricSparkSettings.md) +- [New-FabricSparkCustomPool.ps1](/powershell/FabricACEToolkit/docs/New-FabricSparkCustomPool.md) +- [Remove-FabricSparkCustomPool.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricSparkCustomPool.md) +- [Update-FabricSparkCustomPool.ps1](/powershell/FabricACEToolkit/docs/Update-FabricSparkCustomPool.md) +- [Update-FabricSparkSettings.ps1](/powershell/FabricACEToolkit/docs/Update-FabricSparkSettings.md) + +### Spark Job Definition +- [Get-FabricSparkJobDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinition.md) +- [Get-FabricSparkJobDefinitionDefinition.ps1](/powershell/FabricACEToolkit/docs/Get-FabricSparkJobDefinitionDefinition.md) +- [New-FabricSparkJobDefinition.ps1](/powershell/FabricACEToolkit/docs/New-FabricSparkJobDefinition.md) +- [Remove-FabricSparkJobDefinition.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricSparkJobDefinition.md) +- [Start-FabricSparkJobDefinitionOnDemand.ps1](/powershell/FabricACEToolkit/docs/Start-FabricSparkJobDefinitionOnDemand.md) +- [Update-FabricSparkJobDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinition.md) +- [Update-FabricSparkJobDefinitionDefinition.ps1](/powershell/FabricACEToolkit/docs/Update-FabricSparkJobDefinitionDefinition.md) + +### SQL Endpoints +- [Get-FabricSQLEndpoint.ps1](/powershell/FabricACEToolkit/docs/Get-FabricSQLEndpoint.md) + +### Tenant +- [Get-FabricTenantSetting.ps1](/powershell/FabricACEToolkit/docs/Get-FabricTenantSetting.md) +- [Get-FabricTenantSettingOverridesCapacity.ps1](/powershell/FabricACEToolkit/docs/Get-FabricTenantSettingOverridesCapacity.md) + +## Utils +- [Convert-FromBase64.ps1](/powershell/FabricACEToolkit/docs/Convert-FromBase64.md) +- [Convert-ToBase64.ps1](/powershell/FabricACEToolkit/docs/Convert-ToBase64.md) +- [Get-FabricLongRunningOperation.ps1](/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperation.md) +- [Get-FabricLongRunningOperationResult.ps1](/powershell/FabricACEToolkit/docs/Get-FabricLongRunningOperationResult.md) +- [Set-FabricApiHeaders.ps1](/powershell/FabricACEToolkit/docs/Set-FabricApiHeaders.md) + +### Warehouse +- [Get-FabricWarehouse.ps1](/powershell/FabricACEToolkit/docs/Get-FabricWarehouse.md) +- [New-FabricWarehouse.ps1](/powershell/FabricACEToolkit/docs/New-FabricWarehouse.md) +- [Remove-FabricWarehouse.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricWarehouse.md) +- [Update-FabricWarehouse.ps1](/powershell/FabricACEToolkit/docs/Update-FabricWarehouse.md) + +### Workspace +- [Add-FabricWorkspaceIdentity.ps1](/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceIdentity.md) +- [Add-FabricWorkspaceRoleAssignment.ps1](/powershell/FabricACEToolkit/docs/Add-FabricWorkspaceRoleAssignments.md) +- [Assign-FabricWorkspaceCapacity.ps1](/powershell/FabricACEToolkit/docs/Assign-FabricWorkspaceCapacity.md) +- [Get-FabricWorkspace.ps1](/powershell/FabricACEToolkit/docs/Get-FabricWorkspace.md) +- [Get-FabricWorkspaceRoleAssignment.ps1](/powershell/FabricACEToolkit/docs/Get-FabricWorkspaceRoleAssignment.md) +- [New-FabricWorkspace.ps1](/powershell/FabricACEToolkit/docs/New-FabricWorkspace.md) +- [Remove-FabricWorkspace.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricWorkspace.md) +- [Remove-FabricWorkspaceIdentity.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceIdentity.md) +- [Remove-FabricWorkspaceRoleAssignment.ps1](/powershell/FabricACEToolkit/docs/Remove-FabricWorkspaceRoleAssignment.md) +- [Unassign-FabricWorkspaceCapacity.ps1](/powershell/FabricACEToolkit/docs/Unassign-FabricWorkspaceCapacity.md) +- [Update-FabricWorkspace.ps1](/powershell/FabricACEToolkit/docs/Update-FabricWorkspace.md) +- [Update-FabricWorkspaceRoleAssignment.ps1](/powershell/FabricACEToolkit/docs/Update-FabricWorkspaceRoleAssignment.md) + +## License +This project is licensed under the MIT License. See the [LICENSE](/LICENSE) file for details. \ No newline at end of file