diff --git a/.build/tasks/generateDocs.ps1 b/.build/tasks/generateDocs.ps1 index 3fd2baf7..63b9339b 100644 --- a/.build/tasks/generateDocs.ps1 +++ b/.build/tasks/generateDocs.ps1 @@ -127,7 +127,19 @@ task generate_docs { $newString = "Locale: $HelpCultureInfo" (Get-Content -Path "$Output") -replace $oldString, $newString | Set-Content -Path "$Output" -Encoding utf8 - Copy-Item -Path $Output -Destination $helpDestination -Force + # Skip overwrite if the only change is the auto-updated ms.date front matter field + $destFile = Join-Path $helpDestination (Split-Path $Output -Leaf) + $shouldCopy = $true + if (Test-Path $destFile) { + $newContent = (Get-Content $Output) -replace '^ms\.date:.*$', '' + $existingContent = (Get-Content $destFile) -replace '^ms\.date:.*$', '' + if (($newContent -join "`n") -eq ($existingContent -join "`n")) { + $shouldCopy = $false + } + } + if ($shouldCopy) { + Copy-Item -Path $Output -Destination $helpDestination -Force + } } $newMarkdownModuleFileParams = @{ @@ -141,6 +153,23 @@ task generate_docs { Copy-Item -Path $markdownFile -Destination $helpDestination -Force } - - + # Generate docs/EXPORTED_COMMANDS.md from the en-US help files (single authoritative run) + $exportedCommandsPath = Join-Path $ProjectPath 'docs' 'EXPORTED_COMMANDS.md' + $commandNames = Get-ChildItem -Path $helpDestination -Filter '*.md' -File | + Where-Object { $_.BaseName -ne $ProjectName } | + Select-Object -ExpandProperty BaseName | + Sort-Object -Unique + + $exportedLines = [System.Collections.Generic.List[string]]::new() + $exportedLines.Add("# Exported Commands (derived from ``docs/en-US``)") + $exportedLines.Add("") + $exportedLines.Add("This list was generated from the filenames in ``docs/en-US`` and represents the documented public commands in this repository.") + $exportedLines.Add("") + $exportedLines.Add("Generated on $(Get-Date -Format 'yyyy-MM-dd').") + $exportedLines.Add("") + foreach ($name in $commandNames) { + $exportedLines.Add("- $name") + } + $exportedLines | Set-Content -Path $exportedCommandsPath -Encoding UTF8 + Write-Host "EXPORTED_COMMANDS.md written to: $exportedCommandsPath ($($commandNames.Count) commands)" } diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 016a4f3e..e740b7ba 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,5 +1,6 @@ { "name": "FabricTools PowerShell Dev", + "image": "mcr.microsoft.com/powershell:lts-debian-12", "features": { "ghcr.io/devcontainers/features/powershell:1": {}, "ghcr.io/devcontainers/features/git:1": {}, diff --git a/.github/workflows/deploy-module.yml b/.github/workflows/deploy-module.yml deleted file mode 100644 index 6716045a..00000000 --- a/.github/workflows/deploy-module.yml +++ /dev/null @@ -1,101 +0,0 @@ -on: - push: - branches: - - main - paths-ignore: - - CHANGELOG.md - - .vscode/** - - .github/** - - images/** - - tests/** - - '**.md' - - '**.yml' -env: - buildFolderName: output - buildArtifactName: output - -permissions: - contents: write # to create a release - id-token: write # to use the GitHub OIDC token for authentication - packages: write # to publish the module to the PowerShell Gallery - pull-requests: write # to create a pull request for the changelog - issues: write # to create an issue for the changelog - actions: write # to allow the workflow to run actions - checks: write # to allow the workflow to create checks - statuses: write # to allow the workflow to create statuses - -name: Deploy Module -# This workflow is triggered on push to the main branch and deploys the module to the PowerShell Gallery and creates a GitHub Release. -jobs: - Build_Stage_Package_Module: - name: Package Module - runs-on: ubuntu-latest - steps: - - name: Checkout Code - uses: actions/checkout@v3 - with: - ref: ${{ github.head_ref }} # checkout the correct branch name - fetch-depth: 0 - token: ${{ secrets.GITHUB_TOKEN }} - - name: Install GitVersion - uses: gittools/actions/gitversion/setup@v0.9.15 - with: - versionSpec: 5.x - - name: Evaluate Next Version - uses: gittools/actions/gitversion/execute@v0.9.15 - with: - configFilePath: GitVersion.yml - - name: Build & Package Module - shell: pwsh - run: ./build.ps1 -ResolveDependency -tasks pack - env: - ModuleVersion: ${{ env.GITVERSION_MAJORMINORPATCH }} - - name: Publish Build Artifact - uses: actions/upload-artifact@v4 - with: - name: ${{ env.buildArtifactName }} - path: ${{ env.buildFolderName }}/ - - Deploy_Stage_Deploy_Module: - name: Deploy Module - runs-on: ubuntu-latest - needs: - - Build_Stage_Package_Module - if: ${{ success() && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')) }} - steps: - - name: Checkout Code - uses: actions/checkout@v3 - with: - ref: ${{ github.head_ref }} # checkout the correct branch name - fetch-depth: 0 - token: ${{ secrets.GITHUB_TOKEN }} - - name: Download Build Artifact - uses: actions/download-artifact@v4 - with: - name: ${{ env.buildArtifactName }} - path: ${{ env.buildFolderName }} - - name: Publish Release - shell: pwsh - run: ./build.ps1 -tasks publish - env: - GitHubToken: ${{ secrets.GitHubToken }} - GalleryApiToken: ${{ secrets.GalleryApiToken }} - - name: Merge main -> develop - # This step merges the main branch into the develop branch after a successful deployment. This ensures that the develop branch includes the tag for the latest release. - run: | - git config --local user.email "bot@github.com" - git config --local user.name "GitHub Bot" - git checkout main - git pull - git checkout develop - git pull - git merge --no-ff main -m "Auto-merge main back to dev" - git push - - name: Send Changelog PR - shell: pwsh - run: ./build.ps1 -tasks Create_ChangeLog_GitHub_PR - env: - GitHubToken: ${{ secrets.GitHubToken }} - GalleryApiToken: ${{ secrets.GalleryApiToken }} - ReleaseBranch: main - MainGitBranch: main diff --git a/.github/workflows/deploy-preview-module.yml b/.github/workflows/deploy-preview-module.yml index 7a2eb089..75a0ef7e 100644 --- a/.github/workflows/deploy-preview-module.yml +++ b/.github/workflows/deploy-preview-module.yml @@ -33,7 +33,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} # checkout the correct branch name fetch-depth: 0 @@ -64,7 +64,7 @@ jobs: if: ${{ success() && (github.ref == 'refs/heads/develop' || startsWith(github.ref, 'refs/tags/')) }} steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} # checkout the correct branch name fetch-depth: 0 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 7443ad1d..7a29ac7c 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} # checkout the correct branch name @@ -45,7 +45,7 @@ jobs: - Build_Stage_Package_Module steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} # checkout the correct branch name @@ -71,7 +71,7 @@ jobs: - Build_Stage_Package_Module steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} # checkout the correct branch name @@ -98,7 +98,7 @@ jobs: - Build_Stage_Package_Module steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} # checkout the correct branch name @@ -128,7 +128,7 @@ jobs: - Test_Stage_test_windows_ps steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{github.event.pull_request.head.ref}} # checkout the correct branch name repository: ${{github.event.pull_request.head.repo.full_name}} # checkout the correct branch name diff --git a/.github/workflows/publish-module.yml b/.github/workflows/publish-module.yml index d6c03db8..69e74a09 100644 --- a/.github/workflows/publish-module.yml +++ b/.github/workflows/publish-module.yml @@ -21,7 +21,7 @@ permissions: checks: write # to allow the workflow to create checks statuses: write # to allow the workflow to create statuses -name: Deploy Module (only) +name: Publish Module # This workflow is triggered on push to the main branch and deploys the module to the PowerShell Gallery and creates a GitHub Release. jobs: Build_Stage_Package_Module: @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} # checkout the triggered ref (branch or tag) fetch-depth: 0 @@ -51,7 +51,7 @@ jobs: if: ${{ success() && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')) }} steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v5 with: ref: ${{ github.head_ref }} # checkout the triggered ref (branch or tag) fetch-depth: 0 diff --git a/.gitignore b/.gitignore index 88446bf4..7fc6e780 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,6 @@ package-lock.json # Agents .agents/ + +# Claude Code +.claude/ diff --git a/.specify/memory/constitution.md b/.specify/memory/constitution.md index 113f042d..676732a9 100644 --- a/.specify/memory/constitution.md +++ b/.specify/memory/constitution.md @@ -28,7 +28,7 @@ All contributors MUST follow the project's Code of Conduct. Communication and co ### 2. Develop-in-Source & Reproducible Builds -All development work MUST happen in the `source/` directory. Builds MUST be reproducible using the provided `build.ps1` workflow (examples: `./build.ps1 -ResolveDependency -Tasks noop -UsePSResourceGet` and `./build.ps1 -Tasks build`). The `output/` folder is the canonical build artifact location and MUST not be edited manually; any such edits will be overwritten by the build process. +All development work MUST happen in the `src/` directory. Builds MUST be reproducible using the provided `build.ps1` workflow (examples: `./build.ps1 -ResolveDependency -Tasks noop -UsePSResourceGet` and `./build.ps1 -Tasks build`). The `output/` folder is the canonical build artifact location and MUST not be edited manually; any such edits will be overwritten by the build process. ### 3. Test-First Quality Gates @@ -46,12 +46,12 @@ Dependencies MUST be declared and resolved using the build tools (the manifest's - The module supports PowerShell 5.1 and later as specified in the manifest; contributors MUST ensure compatibility with supported editions. - The module is currently published as Public PREVIEW; it MUST NOT be used in production environments without explicit risk acceptance. -- Required modules listed in `source/FabricTools.psd1` (for example `Az.Accounts`, `MicrosoftPowerBIMgmt.Profile`, `Az.Resources`) MUST be respected; dependency resolution SHOULD use `PSResourceGet` or the included build helpers. +- Required modules listed in `src/FabricTools.psd1` (for example `Az.Accounts`, `MicrosoftPowerBIMgmt.Profile`, `Az.Resources`) MUST be respected; dependency resolution SHOULD use `PSResourceGet` or the included build helpers. - All security disclosures and vulnerability reports MUST follow `SECURITY.md` and be handled confidentially. ## Development Workflow & Quality Gates -- Develop in `source/` (not in `output/`). Use the Sampler structure described in the Wiki and run dependency resolution before development. +- Develop in `src/` (not in `output/`). Use the Sampler structure described in the Wiki and run dependency resolution before development. - Dependency prep example commands (developer guidance): - `./build.ps1 -ResolveDependency -Tasks noop -UsePSResourceGet` — resolve dependencies only. diff --git a/.vscode/settings.json b/.vscode/settings.json index ae0237dc..0492be62 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -20,7 +20,10 @@ "*.ps1xml": "xml" }, "cSpell.words": [ - "Balabuch", + "Tiago", "Balabuch", + "Kamil", "Nowinski", + "Dont", + "Lakehouse", "lakehouses", "buildhelpers", "COMPANYNAME", "endregion", @@ -33,7 +36,14 @@ "PROJECTURI", "pscmdlet", "RELEASENOTES", - "steppable" + "steppable", + "Kusto", + "Eventstream", "Eventstreams", + "Eventhouse", "eventhouses", + "Queryset", "Querysets", + "Datamarts", "Datamart", + "Refreshables", + "ipynb" ], "[markdown]": { "files.trimTrailingWhitespace": false, diff --git a/CHANGELOG.md b/CHANGELOG.md index d1ca7fd6..03176506 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,13 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Added `Get-FabricDataset` cmdlet to retrieve Power BI datasets from My Workspace or a specific workspace, with optional filtering by `DatasetId` or `DatasetName` (`WorkspaceId` parameter, alias `GroupId`) +- Added `Get-FabricDatasetRefreshHistory` cmdlet to retrieve the refresh history of a Power BI dataset, with optional `WorkspaceId` (alias `GroupId`) and `Top` parameters +- Added `Invoke-FabricDatasetRefresh` cmdlet (in `Dataset` folder) to trigger on-demand dataset refreshes, supporting both standard and enhanced refresh parameters (`Type`, `CommitMode`, `MaxParallelism`, `RetryCount`, `Timeout`, `EffectiveDate`, `ApplyRefreshPolicy`, `Objects`) +- Updated unit tests for `Invoke-FabricDatasetRefresh` to cover the new parameter set, alias, ShouldProcess, body construction, and error handling + ### Changed - Renamed `Add-FabricWorkspaceCapacityAssignment` to `Add-FabricWorkspaceCapacity` (issue #42) - Renamed `Remove-FabricWorkspaceCapacityAssignment` to `Remove-FabricWorkspaceCapacity` (issue #42) +- Refactored `Invoke-FabricRestMethod` call in bunch of cmdlets to use hash splatting instead of backtick line continuation (issue #87) +- Refactored cmdlets to use `HandleResponse = $true` on `Invoke-FabricRestMethod`, removing manual status-code switches, LRO polling, and pagination loops from each cmdlet +- `Invoke-FabricRestMethod` handles response by default ### Fixed +- `Connect-FabricAccount` now automatically re-authenticates when MFA or conditional access has expired, without requiring the `-Reset` switch - Made `ReportPathDefinition` parameter optional in `New-FabricReport` (issue #43) - Fixed PowerShell 5.1 compatibility by replacing ternary operators with if-else statements (issue #166) - Added PSFramework as a required module dependency to prevent "not recognized" errors on fresh environments (issue #167) @@ -27,6 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Removed `Invoke-FabricAPIRequest_duplicate` and `Invoke-FabricRestMethodExtended` - Removed all legacy FAB and PowerBI aliases from functions to clean up the module and remove references to old PowerBI-focused codebase (issue #47). - Removed `Register-FabricWorkspaceToCapacity` and `Unregister-FabricWorkspaceToCapacity`, as they are no longer needed (issue #42) +- Removed abandoned `New-FabricNotebookNEW` file (incomplete/broken duplicate of `New-FabricNotebook`) ### Security @@ -90,7 +100,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `Remove-FabricSQLDatabase` uses unified function to handle API results - Updated the `WorkspaceId`, `CapacitiesIds`,`CapacityId`,`CopyJobId`,`datamartId`,`DataPipelineId`,`DataWarehouseGUID`,`DomainId`,`EnvironmentId`,`EventhouseId`,`EventstreamId`,`ExternalDataShareId`,`ItemId`,`KQLDashboardId`,`KQLDatabaseId`,`KQLQuerysetId`,`LakehouseId`,`MirroredDatabaseId`,`MirroredWarehouseId`,`MLExperimentId`,`MLModelId`,`NotebookId`,`operationId`,`PaginatedReportId`,`ParentDomainId`,`parentEventhouseId`,`PrincipalId`,`ReflexId`,`ReportId`,`SemanticModelId`,`SparkCustomPoolId`,`SparkJobDefinitionId`,`SQLDatabaseId`,`SQLEndpointId`,`subscriptionID`,`UserId`,`WarehouseId`,`WorkspaceGUID`,`WorkspaceId`,`WorkspaceIds`, and `WorkspaceRoleAssignmentId` parameters to the datatype GUID [#125](https://github.com/dataplat/FabricTools/issues/125) - Internal function `Invoke-FabricRestMethod`: (#143) - - handles API response, no need to use `Test-FabricApiResponse` from parent public function + - handles API response, no need to use `Test-FabricApiResponse` from parent public function - handles pagination automatically (when `-HandleResponse` is provided) - All Deployment Pipeline functions raise an error when an exception is caught. Used splatting for params. - Refactored SQL Database functions to use enhanced capability in `Invoke-FabricRestMethod`. Used splatting for params. @@ -160,7 +170,7 @@ For a full list of changes and details, please see the commit history. - Removed unnecessary or duplicate functions (e.g., `Get-AllFabricDatasetRefreshes`, `Get-AllFabricCapacities`). - Removed obsolete scripts and commented-out configuration paths. - Removed `Invoke-FabricAPIRequest` and replaced it by `Invoke-FabricRestMethodExtended` -- Removed `Confirm-FabricAuthToken` +- Removed `Confirm-FabricAuthToken` - Renamed `Test-TokenExpired` to `Confirm-TokenState` and extended it using `EnableTokenRefresh` Feature Flag - Removed `Set-FabricApiHeaders` and merged the entire logic to `Connect-FabricAccount` diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..e4dff427 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,129 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +FabricTools is a PowerShell module (~211 public cmdlets) for automating Microsoft Fabric and Power BI administration. It is currently in **Public Preview** and targets PowerShell 5.1+ on Windows and Linux. PRs go against the `batch_changes` branch. + +## Build & Development Commands + +**All work must be done in `/source`, never in `/output` (which is generated).** + +```powershell +# First time / fresh session: resolve all dependencies +./build.ps1 -ResolveDependency -Tasks noop -UsePSResourceGet + +# Build the module (outputs to /output, also imports into session) +./build.ps1 -Tasks build + +# Build then run all tests +./build.ps1 -Tasks build,test + +# Regenerate cmdlet help docs from built module +./build.ps1 -Tasks Generate_help_from_built_module +``` + +```powershell +# Run all Pester tests (after building) +Invoke-Pester ./tests/ + +# Run tests by tag +Invoke-Pester ./tests/ -Tag UnitTests +Invoke-Pester ./tests/ -Tag Public +Invoke-Pester ./tests/ -Tag Changelog +Invoke-Pester ./tests/ -Tag ParameterTypes +Invoke-Pester ./tests/Integration/ -Tag Integration + +# Run a single test file +Invoke-Pester ./tests/Unit/Public/Get-FabricWorkspace.Tests.ps1 +``` + +## Architecture + +### Core API Layer (`src/Private/`) + +All public cmdlets funnel through these private helpers: + +- **`Invoke-FabricRestMethod`** — Universal REST client. Handles pagination (continuation tokens), throttling (HTTP 429), long-running operation polling, and token refresh. Every public cmdlet calls this. +- **`Test-FabricApiResponse`** — Validates API responses and standardizes error handling. +- **`Confirm-TokenState`** — Checks token expiration before each request. +- **`Write-Message`** — Centralized logging via PSFramework. +- **`Get-FabricContinuationToken`** — Pagination support for list operations. +- **`Get-FileDefinitionParts`** — Parses file definitions for item creation/update. + +### Authentication Flow + +`Connect-FabricAccount` (supports user, service principal, credential auth) → `Get-FabricAuthToken` → `Confirm-TokenState` validates on each call → token stored in PSFramework config. + +### Public Cmdlets (`src/Public/`) + +211 cmdlets organized by feature area folders: Capacity, Capacity Assignment, Dashboard, Data Pipeline, Datamart, Deployment Pipeline, Domain, Environment, Eventhouse, Gateway, Item, KQL Database, Lakehouse, ML Experiment, ML Model, Mirrored Database, Notebook, Report, Semantic Model, Spark, Spark Job Definition, Warehouse, Workspace, and more. + +Naming convention: `Verb-FabricNoun` (e.g., `Get-FabricWorkspace`, `New-FabricLakehouse`, `Remove-FabricCapacity`). + +### Configuration + +PSFramework is used for all configuration values (not custom config). Key config keys follow the pattern `FabricTools.FabricApi.*` and `FabricTools.FabricSession.*`. Access via `Get-PSFConfigValue`. + +### Module Dependencies + +``` +Az.Accounts # Azure authentication +Az.Resources # Azure resource management +MicrosoftPowerBIMgmt.Profile # Power BI backward compat +PSFramework # Logging & configuration +``` + +## Invoke-FabricRestMethod Conventions + +In order to prepare input parameters for `Invoke-FabricRestMethod` function - **always use hash splatting** (no backtick line continuation): + +```powershell +$apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Notebook' # item type for log messages + ObjectIdOrName = $NotebookName # id or name for log messages + HandleResponse = $true # delegate ALL response handling to the method +} +$response = Invoke-FabricRestMethod @apiParams +$response +``` + +**Always set `HandleResponse = $true`** — do not write manual `switch ($statusCode)` blocks, `if ($statusCode -ne 200)` checks, or LRO polling loops. `Invoke-FabricRestMethod` handles 200/201/202, HTTP 429 throttling, LRO polling, and pagination internally when this flag is set. + +**`ExtractValue` for list (GET all) operations:** + +- `ExtractValue = 'True'` — always extract `.value` from the response (standard Fabric API list shape) +- `ExtractValue = 'Auto'` — extract `.value` only if it exists +- Wrap the call in `@(...)` to ensure an array when a single item or empty result is returned: `$items = @(Invoke-FabricRestMethod @apiParams)` + +**Table endpoint anomaly** — the `/tables` endpoint returns `.data` instead of `.value`. Use `ExtractValue = 'False'` (or omit it) and manually extract: `@(Invoke-FabricRestMethod @apiParams) | ForEach-Object { $_.data }` + +**`NoWait` parameter** — for operations that support a `$waitForCompletion` bool param, map it as `NoWait = (-not $waitForCompletion)`. + +## Adding a New Cmdlet + +1. Create `src/Public//Verb-FabricNoun.ps1` +2. Add comprehensive comment-based help (`.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.EXAMPLE`) +3. Use `Invoke-FabricRestMethod` for all API calls — follow the hash splatting + `HandleResponse = $true` conventions above +4. Use `Write-Message` (PSFramework) for logging, not `Write-Verbose`/`Write-Host` +5. Create matching test file at `tests/Unit/Verb-FabricNoun.Tests.ps1` +6. Build, then regenerate docs: `./build.ps1 -Tasks Generate_help_from_built_module` +7. Update `CHANGELOG.md` under `## [Unreleased]` using Keep a Changelog format + +## Testing + +- Minimum code coverage threshold: **50%** (configured in `build.yaml`) +- Test files live at `tests/Unit/.Tests.ps1` — one file per cmdlet +- Tests use Pester 5.x syntax with `Describe`/`Context`/`It` blocks and `BeforeAll`/`AfterAll` + +## Commit Message Style + +Follow `.github/copilot-commit-message-instructions.md`: +- Subject line max 50 characters, capitalized, no trailing period +- Use imperative mood ("Add workspace support", not "Added") +- Blank line between subject and body +- Body explains what and why diff --git a/SPECIFICATION.md b/SPECIFICATION.md index b58868c5..421daf0a 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -6,7 +6,7 @@ FabricTools is a PowerShell module that provides administrative and automation c ## Key metadata -- Module manifest: [source/FabricTools.psd1](source/FabricTools.psd1) +- Module manifest: [src/FabricTools.psd1](src/FabricTools.psd1) - `ModuleVersion`: 0.31.0 - `RootModule`: FabricTools.psm1 (generated at build time) - `PowerShellVersion` minimum: 5.1 @@ -15,10 +15,10 @@ FabricTools is a PowerShell module that provides administrative and automation c ## Source layout -- Core module sources: [source](source) - - Public cmdlet implementations: `source/Public/**` - - Private/internal helpers: `source/Private/**` - - Manifest and build-time entrypoints: `source/FabricTools.psd1`, `source/FabricTools.psm1` +- Core module sources: [source](src) + - Public cmdlet implementations: `src/Public/**` + - Private/internal helpers: `src/Private/**` + - Manifest and build-time entrypoints: `src/FabricTools.psd1`, `src/FabricTools.psm1` - Documentation: [docs/en-US](docs/en-US) — one markdown file per cmdlet/area (approx. 214 files) - Tests: [tests](tests) — Pester unit tests (approx. 216 test files, many correlating to cmdlets) - Helpers and CI: `helper/build-and-test.ps1`, `build.ps1`, `azure-pipelines.yml` diff --git a/build.yaml b/build.yaml index b33821d7..4a51c313 100644 --- a/build.yaml +++ b/build.yaml @@ -105,6 +105,7 @@ Pester: # - tests/Unit # - tests/Integration ExcludeTag: + - Integration # - helpQuality # - FunctionalQuality # - TestQuality diff --git a/codecov.yml b/codecov.yml index 847b3d13..c716f376 100644 --- a/codecov.yml +++ b/codecov.yml @@ -27,5 +27,4 @@ coverage: # Use this if there are paths that should not be part of the code coverage, for # example a deprecated function where tests has been removed. #ignore: -# - 'source/Public/Get-Deprecated.ps1' - +# - 'src/Public/Get-Deprecated.ps1' diff --git a/docs/EXPORTED_COMMANDS.md b/docs/EXPORTED_COMMANDS.md index b9bbb861..312e6b7d 100644 --- a/docs/EXPORTED_COMMANDS.md +++ b/docs/EXPORTED_COMMANDS.md @@ -2,12 +2,13 @@ This list was generated from the filenames in `docs/en-US` and represents the documented public commands in this repository. -Generated on 2026-01-11. +Generated on 2026-04-08. - Add-FabricDomainWorkspaceAssignmentByCapacity - Add-FabricDomainWorkspaceAssignmentById - Add-FabricDomainWorkspaceAssignmentByPrincipal - Add-FabricDomainWorkspaceRoleAssignment +- Add-FabricWorkspaceCapacity - Add-FabricWorkspaceCapacityAssignment - Add-FabricWorkspaceIdentity - Add-FabricWorkspaceRoleAssignment @@ -16,25 +17,26 @@ Generated on 2026-01-11. - Convert-FromBase64 - Convert-ToBase64 - Export-FabricItem -- FabricTools - Get-FabricAPIclusterURI - Get-FabricAuthToken +- Get-FabricCapacities - Get-FabricCapacity - Get-FabricCapacityRefreshables - Get-FabricCapacitySkus - Get-FabricCapacityState -- Get-FabricCapacityTenantSettingOverrides - Get-FabricCapacityTenantOverrides +- Get-FabricCapacityTenantSettingOverrides - Get-FabricCapacityWorkload -- Get-FabricCapacities - Get-FabricConfig - Get-FabricConnection - Get-FabricCopyJob - Get-FabricCopyJobDefinition - Get-FabricDashboard -- Get-FabricDataPipeline - Get-FabricDatamart +- Get-FabricDataPipeline +- Get-FabricDataset - Get-FabricDatasetRefreshes +- Get-FabricDatasetRefreshHistory - Get-FabricDebugInfo - Get-FabricDeploymentPipeline - Get-FabricDeploymentPipelineOperation @@ -65,31 +67,28 @@ Generated on 2026-01-11. - Get-FabricLakehouseTable - Get-FabricLongRunningOperation - Get-FabricLongRunningOperationResult -- Get-FabricMLExperiment -- Get-FabricMLModel - Get-FabricMirroredDatabase - Get-FabricMirroredDatabaseDefinition - Get-FabricMirroredDatabaseStatus - Get-FabricMirroredDatabaseTableStatus - Get-FabricMirroredWarehouse +- Get-FabricMLExperiment +- Get-FabricMLModel - Get-FabricNotebook - Get-FabricNotebookDefinition - Get-FabricPaginatedReport -- Get-FabricRecoveryPoint - Get-FabricReflex - Get-FabricReflexDefinition - Get-FabricReport - Get-FabricReportDefinition - Get-FabricSemanticModel - Get-FabricSemanticModelDefinition -- Get-FabricSQLEndpoint +- Get-FabricSparkCustomPool - Get-FabricSparkJobDefinition - Get-FabricSparkJobDefinitionDefinition - Get-FabricSparkSettings -- Get-FabricSparkCustomPool - Get-FabricSQLDatabase -- Get-FabricSparkSettings -- Get-FabricSparkCustomPool +- Get-FabricSQLEndpoint - Get-FabricTenantSetting - Get-FabricUsageMetricsQuery - Get-FabricUserListAccessEntities @@ -100,30 +99,28 @@ Generated on 2026-01-11. - Get-FabricWorkspaceTenantSettingOverrides - Get-FabricWorkspaceUsageMetricsData - Get-FabricWorkspaceUser -- Get-Sha256 - Import-FabricEnvironmentStagingLibrary - Import-FabricItem -- Invoke-FabricAPIRequest +- Invoke-FabricDatasetRefresh - Invoke-FabricKQLCommand - Invoke-FabricRestMethod -- Invoke-FabricDatasetRefresh - New-FabricCopyJob - New-FabricDataPipeline - New-FabricDeploymentPipeline - New-FabricDomain +- New-FabricEnvironment - New-FabricEventhouse - New-FabricEventstream -- New-FabricEnvironment - New-FabricKQLDashboard - New-FabricKQLDatabase - New-FabricKQLQueryset - New-FabricLakehouse +- New-FabricMirroredDatabase - New-FabricMLExperiment - New-FabricMLModel - New-FabricNotebook -- New-FabricNotebookNEW +- New-FabricReflex - New-FabricReport -- New-FabricRecoveryPoint - New-FabricSemanticModel - New-FabricSparkCustomPool - New-FabricSparkJobDefinition @@ -132,8 +129,6 @@ Generated on 2026-01-11. - New-FabricWorkspace - New-FabricWorkspaceUsageMetricsReport - Publish-FabricEnvironment -- Register-FabricWorkspaceToCapacity -- Remove-FabricCapacityTenantSettingOverrides - Remove-FabricCopyJob - Remove-FabricDataPipeline - Remove-FabricDeploymentPipeline @@ -153,29 +148,22 @@ Generated on 2026-01-11. - Remove-FabricMLExperiment - Remove-FabricMLModel - Remove-FabricNotebook -- Remove-FabricPaginatedReport +- Remove-FabricReflex - Remove-FabricReport -- Remove-FabricRecoveryPoint - Remove-FabricSemanticModel - Remove-FabricSparkCustomPool - Remove-FabricSparkJobDefinition - Remove-FabricSQLDatabase - Remove-FabricWarehouse - Remove-FabricWorkspace +- Remove-FabricWorkspaceCapacity - Remove-FabricWorkspaceCapacityAssignment - Remove-FabricWorkspaceFromStage - Remove-FabricWorkspaceIdentity - Remove-FabricWorkspaceRoleAssignment - Resume-FabricCapacity -- Restore-FabricRecoveryPoint - Revoke-FabricCapacityTenantSettingOverrides - Revoke-FabricExternalDataShares -- Register-FabricWorkspaceToCapacity -- Restore-FabricRecoveryPoint -- Resume-FabricCapacity -- Revoke-FabricExternalDataShares -- Revoke-FabricCapacityTenantSettingOverrides -- Set-FabricConfig - Start-FabricDeploymentPipelineStage - Start-FabricLakehouseTableMaintenance - Start-FabricMirroredDatabaseMirroring @@ -183,23 +171,24 @@ Generated on 2026-01-11. - Stop-FabricEnvironmentPublish - Stop-FabricMirroredDatabaseMirroring - Suspend-FabricCapacity -- Unregister-FabricWorkspaceToCapacity +- Update-FabricCapacity - Update-FabricCapacityTenantSettingOverrides - Update-FabricCopyJob - Update-FabricCopyJobDefinition - Update-FabricDataPipeline - Update-FabricDomain - Update-FabricEnvironment +- Update-FabricEnvironmentStagingSparkCompute - Update-FabricEventhouse - Update-FabricEventhouseDefinition - Update-FabricEventstream - Update-FabricEventstreamDefinition +- Update-FabricKQLDashboard +- Update-FabricKQLDashboardDefinition - Update-FabricKQLDatabase - Update-FabricKQLDatabaseDefinition - Update-FabricKQLQueryset - Update-FabricKQLQuerysetDefinition -- Update-FabricKQLDashboard -- Update-FabricKQLDashboardDefinition - Update-FabricLakehouse - Update-FabricMirroredDatabase - Update-FabricMirroredDatabaseDefinition @@ -211,6 +200,7 @@ Generated on 2026-01-11. - Update-FabricReflex - Update-FabricReflexDefinition - Update-FabricReport +- Update-FabricReportDefinition - Update-FabricSemanticModel - Update-FabricSemanticModelDefinition - Update-FabricSparkCustomPool @@ -220,474 +210,4 @@ Generated on 2026-01-11. - Update-FabricWarehouse - Update-FabricWorkspace - Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Write-FabricLakehouseTableData -- Get-FabricDatasetRefreshes -- Get-FabricAPIclusterURI -- Get-FabricEnvironment -- Get-FabricConnection -- Get-FabricConfig -- Get-FabricCapacity -- Get-FabricCapacities -- Get-FabricAuthToken -- Get-FabricDebugInfo -- Get-FabricDeploymentPipeline -- Get-FabricDeploymentPipelineStage -- Get-FabricDeploymentPipelineStageItem -- Get-FabricDeploymentPipelineOperation -- Get-FabricDeploymentPipelineRoleAssignments -- Get-FabricDomainWorkspace -- Get-FabricDomain -- Get-FabricDomainTenantSettingOverrides -- Get-FabricEnvironmentLibrary -- Get-FabricEnvironmentSparkCompute -- Get-FabricEnvironmentStagingLibrary -- Get-FabricEnvironmentStagingSparkCompute -- Get-FabricEventstream -- Get-FabricEventstreamDefinition -- Get-FabricEventhouse -- Get-FabricEventhouseDefinition -- Get-FabricExternalDataShares -- Get-FabricItem -- Get-FabricKQLDatabaseDefinition -- Get-FabricKQLDatabase -- Get-FabricKQLDashboardDefinition -- Get-FabricKQLDashboard -- Get-FabricKQLQuerysetDefinition -- Get-FabricKQLQueryset -- Get-FabricLakehouseTable -- Get-FabricLakehouse -- Get-FabricLongRunningOperation -- Get-FabricLongRunningOperationResult -- Get-FabricMLExperiment -- Get-FabricMLModel -- Get-FabricMirroredDatabaseDefinition -- Get-FabricMirroredDatabase -- Get-FabricMirroredDatabaseStatus -- Get-FabricMirroredDatabaseTableStatus -- Get-FabricMirroredWarehouse -- Get-FabricNotebookDefinition -- Get-FabricNotebook -- Get-FabricPaginatedReport -- Get-FabricRecoveryPoint -- Get-FabricReflexDefinition -- Get-FabricReflex -- Get-FabricReportDefinition -- Get-FabricReport -- Get-FabricSemanticModelDefinition -- Get-FabricSemanticModel -- Get-FabricSparkJobDefinitionDefinition -- Get-FabricSparkJobDefinition -- Get-FabricSparkSettings -- Get-FabricSQLEndpoint -- Get-FabricSQLDatabase -- Get-FabricSparkCustomPool -- Get-FabricTenantSetting -- Get-FabricUsageMetricsQuery -- Get-FabricUserListAccessEntities -- Get-FabricWarehouse -- Get-FabricWorkspaceUsageMetricsData -- Get-FabricWorkspaceTenantSettingOverrides -- Get-FabricWorkspaceRoleAssignment -- Get-FabricWorkspaceDatasetRefreshes -- Get-FabricWorkspaceUser -- Get-FabricWorkspace -- Get-Sha256 -- Convert-FromBase64 -- Convert-ToBase64 -- Connect-FabricAccount -- Import-FabricEnvironmentStagingLibrary -- Import-FabricItem -- New-FabricWorkspaceUsageMetricsReport -- New-FabricWorkspace -- New-FabricWarehouse -- New-FabricSQLDatabase -- New-FabricSparkJobDefinition -- New-FabricSparkCustomPool -- New-FabricReport -- New-FabricRecoveryPoint -- New-FabricReflex -- New-FabricSemanticModel -- New-FabricNotebookNEW -- New-FabricNotebook -- New-FabricMLModel -- New-FabricMLExperiment -- New-FabricDataPipeline -- New-FabricDomain -- New-FabricDeploymentPipeline -- New-FabricCopyJob -- Remove-FabricKQLQueryset -- Remove-FabricMirroredDatabase -- Remove-FabricMLExperiment -- Remove-FabricMLModel -- Remove-FabricNotebook -- Remove-FabricPaginatedReport -- Remove-FabricReport -- Remove-FabricRecoveryPoint -- Remove-FabricSemanticModel -- Remove-FabricSparkCustomPool -- Remove-FabricSparkJobDefinition -- Remove-FabricSQLDatabase -- Remove-FabricWarehouse -- Remove-FabricWorkspace -- Remove-FabricWorkspaceFromStage -- Remove-FabricWorkspaceIdentity -- Remove-FabricWorkspaceRoleAssignment -- Remove-FabricWorkspaceCapacityAssignment -- Remove-FabricWorkspaceRoleAssignment -- Remove-FabricWorkspaceRoleAssignment -- Register-FabricWorkspaceToCapacity -- Register-FabricWorkspaceToCapacity -- Publish-FabricEnvironment -- Write-FabricLakehouseTableData -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspace -- Update-FabricWarehouse -- Update-FabricSparkSettings -- Update-FabricSparkJobDefinitionDefinition -- Update-FabricSparkJobDefinition -- Update-FabricSparkCustomPool -- Update-FabricMLModel -- Update-FabricMLExperiment -- Update-FabricNotebookDefinition -- Update-FabricNotebook -- Update-FabricMirroredDatabaseDefinition -- Update-FabricMirroredDatabase -- Update-FabricLakehouse -- Update-FabricKQLDashboardDefinition -- Update-FabricKQLDashboard -- Update-FabricKQLDatabaseDefinition -- Update-FabricKQLDatabase -- Update-FabricKQLQuerysetDefinition -- Update-FabricKQLQueryset -- Update-FabricKQLQueryset -- Update-FabricKQLQuerysetDefinition -- Update-FabricEventstreamDefinition -- Update-FabricEventstream -- Update-FabricEventhouseDefinition -- Update-FabricEventhouse -- Update-FabricEnvironmentStagingSparkCompute -- Update-FabricEventhouse -- Update-FabricEventhouseDefinition -- Update-FabricEventstream -- Update-FabricEventstreamDefinition -- Update-FabricDomain -- Update-FabricDataPipeline -- Update-FabricCopyJob -- Update-FabricCopyJobDefinition -- Update-FabricCapacityTenantSettingOverrides -- Remove-FabricDomain -- Remove-FabricDomainWorkspaceAssignment -- Remove-FabricDomainWorkspaceRoleAssignment -- Remove-FabricDomainWorkspaceRoleAssignment -- Remove-FabricDomainWorkspaceRoleAssignment -- Remove-FabricEnvironment -- Remove-FabricEnvironmentStagingLibrary -- Remove-FabricEventstream -- Remove-FabricEventhouse -- Remove-FabricItem -- Remove-FabricKQLDashboard -- Remove-FabricKQLDatabase -- Remove-FabricKQLQueryset -- Remove-FabricLakehouse -- Remove-FabricMirroredDatabase -- Remove-FabricMLExperiment -- Remove-FabricMLModel -- Remove-FabricNotebook -- Remove-FabricPaginatedReport -- Remove-FabricReport -- Remove-FabricRecoveryPoint -- Remove-FabricSemanticModel -- Remove-FabricSparkCustomPool -- Remove-FabricSparkJobDefinition -- Remove-FabricSQLDatabase -- Remove-FabricWarehouse -- Remove-FabricWorkspace -- Remove-FabricWorkspaceFromStage -- Remove-FabricWorkspaceIdentity -- Remove-FabricWorkspaceRoleAssignment -- Remove-FabricWorkspaceCapacityAssignment -- Remove-FabricWorkspaceRoleAssignment -- Remove-FabricWorkspaceRoleAssignment -- Update-FabricCapacityTenantSettingOverrides -- Update-FabricCopyJob -- Update-FabricCopyJobDefinition -- Update-FabricDataPipeline -- Update-FabricDomain -- Update-FabricEnvironment -- Update-FabricEventhouse -- Update-FabricEventstream -- Update-FabricEventstreamDefinition -- Update-FabricKQLDatabase -- Update-FabricKQLDatabaseDefinition -- Update-FabricKQLQueryset -- Update-FabricKQLQuerysetDefinition -- Update-FabricKQLDashboard -- Update-FabricKQLDashboardDefinition -- Update-FabricLakehouse -- Update-FabricMirroredDatabase -- Update-FabricMirroredDatabaseDefinition -- Update-FabricMLExperiment -- Update-FabricMLModel -- Update-FabricNotebookDefinition -- Update-FabricNotebook -- Update-FabricPaginatedReport -- Update-FabricReflexDefinition -- Update-FabricReflex -- Update-FabricReport -- Update-FabricSemanticModelDefinition -- Update-FabricSemanticModel -- Update-FabricSparkCustomPool -- Update-FabricSparkJobDefinitionDefinition -- Update-FabricSparkJobDefinition -- Update-FabricSparkSettings -- Update-FabricWarehouse -- Update-FabricWorkspace -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Write-FabricLakehouseTableData -- Get-FabricAPIclusterURI -- Get-FabricAuthToken -- Get-FabricCapacities -- Get-FabricCapacity -- Get-FabricCapacityRefreshables -- Get-FabricCapacitySkus -- Get-FabricCapacityState -- Get-FabricCapacityTenantSettingOverrides -- Get-FabricCapacityTenantOverrides -- Get-FabricCapacityWorkload -- Get-FabricConfig -- Get-FabricConnection -- Get-FabricDashboard -- Get-FabricCopyJob -- Get-FabricCopyJobDefinition -- Get-FabricDatamart -- Get-FabricDataPipeline -- Get-FabricDatasetRefreshes -- Get-FabricDebugInfo -- Get-FabricDeploymentPipelineRoleAssignments -- Get-FabricDeploymentPipelineOperation -- Get-FabricDeploymentPipelineStageItem -- Get-FabricDeploymentPipelineStage -- Get-FabricDeploymentPipeline -- Get-FabricDomainTenantSettingOverrides -- Get-FabricDomainWorkspace -- Get-FabricDomain -- Get-FabricEnvironmentStagingSparkCompute -- Get-FabricEnvironmentStagingLibrary -- Get-FabricEnvironmentSparkCompute -- Get-FabricEnvironmentLibrary -- Get-FabricEnvironment -- Get-FabricEventstreamDefinition -- Get-FabricEventstream -- Get-FabricEventhouseDefinition -- Get-FabricEventhouse -- Get-FabricExternalDataShares -- Get-FabricItem -- Get-FabricKQLQuerysetDefinition -- Get-FabricKQLQueryset -- Get-FabricKQLDatabaseDefinition -- Get-FabricKQLDatabase -- Get-FabricKQLDashboardDefinition -- Get-FabricKQLDashboard -- Get-FabricLakehouseTable -- Get-FabricLakehouse -- Get-FabricLongRunningOperationResult -- Get-FabricLongRunningOperation -- Get-FabricMLExperiment -- Get-FabricMLModel -- Get-FabricMirroredDatabaseTableStatus -- Get-FabricMirroredDatabaseStatus -- Get-FabricMirroredDatabaseDefinition -- Get-FabricMirroredDatabase -- Get-FabricMirroredWarehouse -- Get-FabricNotebookDefinition -- Get-FabricNotebook -- Get-FabricPaginatedReport -- Get-FabricRecoveryPoint -- Get-FabricReflexDefinition -- Get-FabricReflex -- Get-FabricReportDefinition -- Get-FabricReport -- Get-FabricSemanticModelDefinition -- Get-FabricSemanticModel -- Get-FabricSparkJobDefinitionDefinition -- Get-FabricSparkJobDefinition -- Get-FabricSparkSettings -- Get-FabricSQLEndpoint -- Get-FabricSQLDatabase -- Get-FabricSparkCustomPool -- Get-FabricTenantSetting -- Get-FabricUsageMetricsQuery -- Get-FabricUserListAccessEntities -- Get-FabricWarehouse -- Get-FabricWorkspaceUsageMetricsData -- Get-FabricWorkspaceTenantSettingOverrides -- Get-FabricWorkspaceRoleAssignment -- Get-FabricWorkspaceDatasetRefreshes -- Get-FabricWorkspaceUser -- Get-FabricWorkspace -- Get-Sha256 -- Convert-FromBase64 -- Convert-ToBase64 -- Connect-FabricAccount -- Import-FabricEnvironmentStagingLibrary -- Import-FabricItem -- New-FabricWorkspaceUsageMetricsReport -- New-FabricWorkspace -- New-FabricWarehouse -- New-FabricSQLDatabase -- New-FabricSparkJobDefinition -- New-FabricSparkCustomPool -- New-FabricReport -- New-FabricRecoveryPoint -- New-FabricReflex -- New-FabricSemanticModel -- New-FabricNotebookNEW -- New-FabricNotebook -- New-FabricMLModel -- New-FabricMLExperiment -- New-FabricDataPipeline -- New-FabricDomain -- New-FabricDeploymentPipeline -- New-FabricCopyJob -- Remove-FabricKQLQueryset -- Remove-FabricMirroredDatabase -- Remove-FabricMLExperiment -- Remove-FabricMLModel -- Remove-FabricNotebook -- Remove-FabricPaginatedReport -- Remove-FabricReport -- Remove-FabricRecoveryPoint -- Remove-FabricSemanticModel -- Remove-FabricSparkCustomPool -- Remove-FabricSparkJobDefinition -- Remove-FabricSQLDatabase -- Remove-FabricWarehouse -- Remove-FabricWorkspace -- Remove-FabricWorkspaceFromStage -- Remove-FabricWorkspaceIdentity -- Remove-FabricWorkspaceRoleAssignment -- Remove-FabricWorkspaceCapacityAssignment -- Remove-FabricWorkspaceRoleAssignment -- Remove-FabricWorkspaceRoleAssignment -- Register-FabricWorkspaceToCapacity -- Register-FabricWorkspaceToCapacity -- Publish-FabricEnvironment -- Write-FabricLakehouseTableData -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspace -- Update-FabricWarehouse -- Update-FabricSparkSettings -- Update-FabricSparkJobDefinitionDefinition -- Update-FabricSparkJobDefinition -- Update-FabricSparkCustomPool -- Update-FabricMLModel -- Update-FabricMLExperiment -- Update-FabricNotebookDefinition -- Update-FabricNotebook -- Update-FabricMirroredDatabaseDefinition -- Update-FabricMirroredDatabase -- Update-FabricLakehouse -- Update-FabricKQLDashboardDefinition -- Update-FabricKQLDashboard -- Update-FabricKQLDatabaseDefinition -- Update-FabricKQLDatabase -- Update-FabricKQLQuerysetDefinition -- Update-FabricKQLQueryset -- Update-FabricKQLQueryset -- Update-FabricKQLQuerysetDefinition -- Update-FabricEventstreamDefinition -- Update-FabricEventstream -- Update-FabricEventhouseDefinition -- Update-FabricEventhouse -- Update-FabricEnvironmentStagingSparkCompute -- Update-FabricEventhouse -- Update-FabricEventhouseDefinition -- Update-FabricEventstream -- Update-FabricEventstreamDefinition -- Update-FabricDomain -- Update-FabricDataPipeline -- Update-FabricCopyJob -- Update-FabricCopyJobDefinition -- Update-FabricCapacityTenantSettingOverrides -- Remove-FabricDomain -- Remove-FabricDomainWorkspaceAssignment -- Remove-FabricDomainWorkspaceRoleAssignment -- Remove-FabricDomainWorkspaceRoleAssignment -- Remove-FabricDomainWorkspaceRoleAssignment -- Remove-FabricEnvironment -- Remove-FabricEnvironmentStagingLibrary -- Remove-FabricEventstream -- Remove-FabricEventhouse -- Remove-FabricItem -- Remove-FabricKQLDashboard -- Remove-FabricKQLDatabase -- Remove-FabricKQLQueryset -- Remove-FabricLakehouse -- Remove-FabricMirroredDatabase -- Remove-FabricMLExperiment -- Remove-FabricMLModel -- Remove-FabricNotebook -- Remove-FabricPaginatedReport -- Remove-FabricReport -- Remove-FabricRecoveryPoint -- Remove-FabricSemanticModel -- Remove-FabricSparkCustomPool -- Remove-FabricSparkJobDefinition -- Remove-FabricSQLDatabase -- Remove-FabricWarehouse -- Remove-FabricWorkspace -- Remove-FabricWorkspaceFromStage -- Remove-FabricWorkspaceIdentity -- Remove-FabricWorkspaceRoleAssignment -- Remove-FabricWorkspaceCapacityAssignment -- Update-FabricCapacityTenantSettingOverrides -- Update-FabricCopyJob -- Update-FabricCopyJobDefinition -- Update-FabricDataPipeline -- Update-FabricDomain -- Update-FabricEnvironment -- Update-FabricEventhouse -- Update-FabricEventstream -- Update-FabricEventstreamDefinition -- Update-FabricKQLDatabase -- Update-FabricKQLDatabaseDefinition -- Update-FabricKQLQueryset -- Update-FabricKQLQuerysetDefinition -- Update-FabricKQLDashboard -- Update-FabricKQLDashboardDefinition -- Update-FabricLakehouse -- Update-FabricMirroredDatabase -- Update-FabricMirroredDatabaseDefinition -- Update-FabricMLExperiment -- Update-FabricMLModel -- Update-FabricNotebookDefinition -- Update-FabricNotebook -- Update-FabricPaginatedReport -- Update-FabricReflexDefinition -- Update-FabricReflex -- Update-FabricReport -- Update-FabricSemanticModelDefinition -- Update-FabricSemanticModel -- Update-FabricSparkCustomPool -- Update-FabricSparkJobDefinitionDefinition -- Update-FabricSparkJobDefinition -- Update-FabricSparkSettings -- Update-FabricWarehouse -- Update-FabricWorkspace -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment -- Update-FabricWorkspaceRoleAssignment - Write-FabricLakehouseTableData diff --git a/docs/en-US/FabricTools.md b/docs/en-US/FabricTools.md index fbb8c4c6..586938f7 100644 --- a/docs/en-US/FabricTools.md +++ b/docs/en-US/FabricTools.md @@ -5,7 +5,7 @@ HelpInfoUri: https://www.github.com/dataplat/FabricTools Locale: en-US Module Guid: f2a0f9e6-fab6-41fc-9e1c-0c94ff38f794 Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: FabricTools Module --- @@ -88,7 +88,7 @@ Retrieves capacity details from a specified Microsoft Fabric workspace. ### [Get-FabricCapacityRefreshables](Get-FabricCapacityRefreshables.md) -Retrieves the top refreshable capacities for the tenant. +Returns a list of refreshables for all capacities that the user has access to. ### [Get-FabricCapacitySkus](Get-FabricCapacitySkus.md) @@ -138,10 +138,18 @@ Retrieves datamarts from a specified workspace. Retrieves data pipelines from a specified Microsoft Fabric workspace. +### [Get-FabricDataset](Get-FabricDataset.md) + +Retrieves one or more Power BI datasets from My Workspace or a specific workspace. + ### [Get-FabricDatasetRefreshes](Get-FabricDatasetRefreshes.md) Retrieves the refresh history of a specified dataset in a PowerBI workspace. +### [Get-FabricDatasetRefreshHistory](Get-FabricDatasetRefreshHistory.md) + +Retrieves the refresh history of a Power BI dataset. + ### [Get-FabricDebugInfo](Get-FabricDebugInfo.md) Shows internal debug information about the current Azure & Fabric sessions & Fabric config. @@ -302,10 +310,6 @@ Retrieves the definition of a notebook from a specific workspace in Microsoft Fa Retrieves paginated report details from a specified Microsoft Fabric workspace. -### [Get-FabricRecoveryPoint](Get-FabricRecoveryPoint.md) - -Get a list of Fabric recovery points. - ### [Get-FabricReflex](Get-FabricReflex.md) Retrieves Reflex details from a specified Microsoft Fabric workspace. @@ -394,10 +398,6 @@ Retrieves workspace usage metrics data. Retrieves the user(s) of a workspace. -### [Get-Sha256](Get-Sha256.md) - -Calculates the SHA256 hash of a string. - ### [Import-FabricEnvironmentStagingLibrary](Import-FabricEnvironmentStagingLibrary.md) Uploads a library to the staging environment in a Microsoft Fabric workspace. @@ -408,7 +408,7 @@ Imports items using the Power BI Project format (PBIP) into a Fabric workspace f ### [Invoke-FabricDatasetRefresh](Invoke-FabricDatasetRefresh.md) -This function invokes a refresh of a PowerBI dataset +Triggers a refresh of a Power BI dataset. ### [Invoke-FabricKQLCommand](Invoke-FabricKQLCommand.md) @@ -478,14 +478,6 @@ Creates a new ML Model in a specified Microsoft Fabric workspace. Creates a new notebook in a specified Microsoft Fabric workspace. -### [New-FabricNotebookNEW](New-FabricNotebookNEW.md) - -Creates a new notebook in a specified Microsoft Fabric workspace. - -### [New-FabricRecoveryPoint](New-FabricRecoveryPoint.md) - -Create a recovery point for a Fabric data warehouse - ### [New-FabricReflex](New-FabricReflex.md) Creates a new Reflex in a specified Microsoft Fabric workspace. @@ -602,10 +594,6 @@ Removes an ML Model from a specified Microsoft Fabric workspace. Deletes an Notebook from a specified workspace in Microsoft Fabric. -### [Remove-FabricRecoveryPoint](Remove-FabricRecoveryPoint.md) - -Remove a selected Fabric Recovery Point. - ### [Remove-FabricReflex](Remove-FabricReflex.md) Removes an Reflex from a specified Microsoft Fabric workspace. @@ -654,10 +642,6 @@ Deprovisions the Managed Identity for a specified Fabric workspace. Removes a role assignment from a Fabric workspace. -### [Restore-FabricRecoveryPoint](Restore-FabricRecoveryPoint.md) - -Restore a Fabric data warehouse to a specified restore pont. - ### [Resume-FabricCapacity](Resume-FabricCapacity.md) Resumes a capacity. @@ -670,10 +654,6 @@ Removes a tenant setting override from a specific capacity in the Fabric tenant. Retrieves External Data Shares details from a specified Microsoft Fabric. -### [Set-FabricConfig](Set-FabricConfig.md) - -Register the configuration for use with all functions in the FabricTools module. - ### [Start-FabricDeploymentPipelineStage](Start-FabricDeploymentPipelineStage.md) Deploys items from one stage to another in a deployment pipeline. @@ -861,4 +841,3 @@ Updates the role assignment for a specific principal in a Fabric workspace. ### [Write-FabricLakehouseTableData](Write-FabricLakehouseTableData.md) Loads data into a specified table in a Lakehouse within a Fabric workspace. - diff --git a/docs/en-US/Get-FabricCapacityRefreshables.md b/docs/en-US/Get-FabricCapacityRefreshables.md index 40f031c6..01af948c 100644 --- a/docs/en-US/Get-FabricCapacityRefreshables.md +++ b/docs/en-US/Get-FabricCapacityRefreshables.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Get-FabricCapacityRefreshables --- @@ -13,7 +13,7 @@ title: Get-FabricCapacityRefreshables ## SYNOPSIS -Retrieves the top refreshable capacities for the tenant. +Returns a list of refreshables for all capacities that the user has access to. ## SYNTAX @@ -27,25 +27,38 @@ Get-FabricCapacityRefreshables [[-top] ] [] ## DESCRIPTION -The Get-FabricCapacityRefreshables function retrieves the top refreshable capacities for the tenant. -It supports multiple aliases for flexibility. +The Get-FabricCapacityRefreshables function returns refreshables (datasets with refresh activity) +for all capacities the user has access to. +Power BI retains a seven-day refresh history for each +dataset, up to a maximum of 60 refreshes. + +Requires scope: Capacity.Read.All or Capacity.ReadWrite.All ## EXAMPLES ### EXAMPLE 1 -This example retrieves the top 5 refreshable capacities for the tenant. +Retrieves the top 10 refreshables across all capacities. ```powershell -Get-FabricCapacityRefreshables -top 5 +Get-FabricCapacityRefreshables -top 10 +``` + +### EXAMPLE 2 + +Retrieves the top 5 refreshables with capacity details expanded. + +```powershell +Get-FabricCapacityRefreshables -top 5 -expand 'capacity' ``` ## PARAMETERS ### -top -The number of top refreshable capacities to retrieve. -This is a mandatory parameter. +Required. +Returns only the first n results. +Must be a positive integer (minimum: 1). ```yaml Type: System.String @@ -77,9 +90,6 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## NOTES -The function retrieves the PowerBI access token and makes a GET request to the PowerBI API to retrieve the top refreshable capacities. -It then returns the 'value' property of the response, which contains the capacities. - Author: Ioana Bouariu ## RELATED LINKS diff --git a/docs/en-US/Get-FabricDataset.md b/docs/en-US/Get-FabricDataset.md new file mode 100644 index 00000000..f2c9d698 --- /dev/null +++ b/docs/en-US/Get-FabricDataset.md @@ -0,0 +1,163 @@ +--- +document type: cmdlet +external help file: FabricTools-Help.xml +HelpUri: '' +Locale: en-US +Module Name: FabricTools +ms.date: 04/08/2026 +PlatyPS schema version: 2024-05-01 +title: Get-FabricDataset +--- + +# Get-FabricDataset + +## SYNOPSIS + +Retrieves one or more Power BI datasets from My Workspace or a specific workspace. + +## SYNTAX + +### __AllParameterSets + +``` +Get-FabricDataset [[-WorkspaceId] ] [[-DatasetId] ] [[-DatasetName] ] + [] +``` + +## ALIASES + +## DESCRIPTION + +Calls the Power BI REST API to list datasets. +When `GroupId` is supplied the request targets a specific workspace +(`groups/{groupId}/datasets`); otherwise it targets My Workspace (`datasets`). + +Optionally filter the results to a single dataset by `DatasetId` or `DatasetName`. + +## EXAMPLES + +### EXAMPLE 1 + +Retrieves all datasets from My Workspace. + +```powershell +Get-FabricDataset +``` + +### EXAMPLE 2 + +Retrieves all datasets from a specific workspace. + +```powershell +Get-FabricDataset -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" +``` + +### EXAMPLE 3 + +Retrieves a specific dataset by name from a workspace. + +```powershell +Get-FabricDataset -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" -DatasetName "Sales Model" +``` + +### EXAMPLE 4 + +Retrieves a specific dataset by ID from My Workspace. + +```powershell +Get-FabricDataset -DatasetId "12345678-90ab-cdef-1234-567890abcdef" +``` + +## PARAMETERS + +### -DatasetId + +(Optional) The unique identifier of a specific dataset to return. +Cannot be combined with `DatasetName`. + +```yaml +Type: System.Guid +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 1 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -DatasetName + +(Optional) The display name of a specific dataset to return. +Cannot be combined with `DatasetId`. + +```yaml +Type: System.String +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 2 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -WorkspaceId + +(Optional) The unique identifier of the workspace to query. +When omitted, datasets from My Workspace are returned. + +```yaml +Type: System.Guid +DefaultValue: '' +SupportsWildcards: false +Aliases: +- GroupId +ParameterSets: +- Name: (All) + Position: 0 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, +-ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +- Requires a valid Power BI / Fabric token (call `Connect-FabricAccount` first). +- Calls `Confirm-TokenState` to ensure token validity before making the API request. +- Callers with Read-only access to a workspace may receive a limited response + (only `id` and `name` fields) from the in-group endpoint. + +Author: Kamil Nowinski + +## RELATED LINKS + +{{ Fill in the related links here }} + diff --git a/docs/en-US/Get-FabricDatasetRefreshHistory.md b/docs/en-US/Get-FabricDatasetRefreshHistory.md new file mode 100644 index 00000000..9a3ff6de --- /dev/null +++ b/docs/en-US/Get-FabricDatasetRefreshHistory.md @@ -0,0 +1,150 @@ +--- +document type: cmdlet +external help file: FabricTools-Help.xml +HelpUri: '' +Locale: en-US +Module Name: FabricTools +ms.date: 04/08/2026 +PlatyPS schema version: 2024-05-01 +title: Get-FabricDatasetRefreshHistory +--- + +# Get-FabricDatasetRefreshHistory + +## SYNOPSIS + +Retrieves the refresh history of a Power BI dataset. + +## SYNTAX + +### __AllParameterSets + +``` +Get-FabricDatasetRefreshHistory [-DatasetId] [[-WorkspaceId] ] [[-Top] ] + [] +``` + +## ALIASES + +## DESCRIPTION + +Calls the Power BI REST API to retrieve the refresh history for a specified dataset. +When `GroupId` is supplied the request targets the dataset inside a specific workspace +(`groups/{groupId}/datasets/{datasetId}/refreshes`); otherwise it targets the dataset +in My Workspace (`datasets/{datasetId}/refreshes`). + +## EXAMPLES + +### EXAMPLE 1 + +Retrieves the refresh history for a dataset in My Workspace. + +```powershell +Get-FabricDatasetRefreshHistory -DatasetId "12345678-90ab-cdef-1234-567890abcdef" +``` + +### EXAMPLE 2 + +Retrieves the last 10 refresh history entries for a dataset in a specific workspace. + +```powershell +Get-FabricDatasetRefreshHistory ` + -DatasetId "12345678-90ab-cdef-1234-567890abcdef" ` + -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" ` + -Top 10 +``` + +## PARAMETERS + +### -DatasetId + +(Mandatory) The unique identifier of the dataset whose refresh history to retrieve. + +```yaml +Type: System.Guid +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 0 + IsRequired: true + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -Top + +(Optional) The number of refresh history entries to return. +Must be at least 1. +Defaults to 60 (Power BI API default). + +```yaml +Type: System.Int32 +DefaultValue: 0 +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 2 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -WorkspaceId + +(Optional) The unique identifier of the workspace that contains the dataset. +When omitted, the My Workspace endpoint is used. + +```yaml +Type: System.Guid +DefaultValue: '' +SupportsWildcards: false +Aliases: +- GroupId +ParameterSets: +- Name: (All) + Position: 1 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### CommonParameters + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, +-ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES + +- Requires a valid Power BI / Fabric token (call `Connect-FabricAccount` first). +- Calls `Confirm-TokenState` to ensure token validity before making the API request. +- OneDrive refresh history is not returned by the Power BI API. +- The API retains at most 60 entries; entries older than 3 days are pruned once more + than 20 exist. + +Author: Kamil Nowinski + +## RELATED LINKS + +{{ Fill in the related links here }} + diff --git a/docs/en-US/Get-FabricLakehouse.md b/docs/en-US/Get-FabricLakehouse.md index a36a70ca..b63ee473 100644 --- a/docs/en-US/Get-FabricLakehouse.md +++ b/docs/en-US/Get-FabricLakehouse.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Get-FabricLakehouse --- @@ -130,7 +130,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Get-FabricLakehouseTable.md b/docs/en-US/Get-FabricLakehouseTable.md index c17ffa96..17b1a3a2 100644 --- a/docs/en-US/Get-FabricLakehouseTable.md +++ b/docs/en-US/Get-FabricLakehouseTable.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Get-FabricLakehouseTable --- @@ -101,7 +101,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## NOTES -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Get-FabricNotebook.md b/docs/en-US/Get-FabricNotebook.md index 69686fcf..b0e313df 100644 --- a/docs/en-US/Get-FabricNotebook.md +++ b/docs/en-US/Get-FabricNotebook.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Get-FabricNotebook --- @@ -130,7 +130,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Get-FabricNotebookDefinition.md b/docs/en-US/Get-FabricNotebookDefinition.md index 41108dc7..0bf21554 100644 --- a/docs/en-US/Get-FabricNotebookDefinition.md +++ b/docs/en-US/Get-FabricNotebookDefinition.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Get-FabricNotebookDefinition --- @@ -134,7 +134,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Handles long-running operations asynchronously. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Get-FabricRecoveryPoint.md b/docs/en-US/Get-FabricRecoveryPoint.md deleted file mode 100644 index 5ca07680..00000000 --- a/docs/en-US/Get-FabricRecoveryPoint.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -document type: cmdlet -external help file: FabricTools-Help.xml -HelpUri: '' -Locale: en-US -Module Name: FabricTools -ms.date: 04/01/2026 -PlatyPS schema version: 2024-05-01 -title: Get-FabricRecoveryPoint ---- - -# Get-FabricRecoveryPoint - -## SYNOPSIS - -Get a list of Fabric recovery points. - -## SYNTAX - -### __AllParameterSets - -``` -Get-FabricRecoveryPoint [[-WorkspaceGUID] ] [[-DataWarehouseGUID] ] - [[-BaseUrl] ] [[-Since] ] [[-Type] ] [[-CreateTime] ] -``` - -## ALIASES - -## DESCRIPTION - -Get a list of Fabric recovery points. -Results can be filter by date or type. - -## EXAMPLES - -### EXAMPLE 1 - -Gets all the available recovery points for the specified data warehouse, in the specified workspace. - -```powershell -Get-FabricRecoveryPoint -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -``` - -## PARAMETERS - -### -BaseUrl - -Defaults to api.powerbi.com - -```yaml -Type: System.String -DefaultValue: api.powerbi.com -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 2 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -CreateTime - -The specific unique time of the restore point to remove. -Get this from Get-FabricRecoveryPoint. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 5 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -DataWarehouseGUID - -The GUID for the data warehouse which we want to retrieve restore points for. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Since - -Filter the results to only include restore points created after this date. - -```yaml -Type: System.DateTime -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 3 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Type - -Filter the results to only include restore points of this type. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 4 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WorkspaceGUID - -This is the workspace GUID in which the data warehouse resides. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -## INPUTS - -## OUTPUTS - -## NOTES - -Based on API calls from this blog post: https://blog.fabric.microsoft.com/en-US/blog/the-art-of-data-warehouse-recovery-within-microsoft-fabric/ - -Author: Jess Pomfret - -## RELATED LINKS - -{{ Fill in the related links here }} - diff --git a/docs/en-US/Get-Sha256.md b/docs/en-US/Get-Sha256.md deleted file mode 100644 index 23dc3bdf..00000000 --- a/docs/en-US/Get-Sha256.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -document type: cmdlet -external help file: FabricTools-Help.xml -HelpUri: '' -Locale: en-US -Module Name: FabricTools -ms.date: 04/01/2026 -PlatyPS schema version: 2024-05-01 -title: Get-Sha256 ---- - -# Get-Sha256 - -## SYNOPSIS - -Calculates the SHA256 hash of a string. - -## SYNTAX - -### __AllParameterSets - -``` -Get-Sha256 [[-string] ] -``` - -## ALIASES - -## DESCRIPTION - -The Get-Sha256 function calculates the SHA256 hash of a string. - -## EXAMPLES - -### EXAMPLE 1 - -Get-Sha256 -string "your-string" - -This example calculates the SHA256 hash of a string. - -## PARAMETERS - -### -string - -The string to hash. -This is a mandatory parameter. - -```yaml -Type: System.Object -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -## INPUTS - -## OUTPUTS - -## NOTES - -The function creates a new SHA256CryptoServiceProvider object, converts the string to a byte array using UTF8 encoding, computes the SHA256 hash of the byte array, converts the hash to a string and removes any hyphens, and returns the resulting hash. - -Author: Ioana Bouariu - -## RELATED LINKS - -{{ Fill in the related links here }} - diff --git a/docs/en-US/Invoke-FabricDatasetRefresh.md b/docs/en-US/Invoke-FabricDatasetRefresh.md index dfd160e3..358f423f 100644 --- a/docs/en-US/Invoke-FabricDatasetRefresh.md +++ b/docs/en-US/Invoke-FabricDatasetRefresh.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Invoke-FabricDatasetRefresh --- @@ -13,48 +13,148 @@ title: Invoke-FabricDatasetRefresh ## SYNOPSIS -This function invokes a refresh of a PowerBI dataset +Triggers a refresh of a Power BI dataset. ## SYNTAX -### DatasetId +### __AllParameterSets ``` -Invoke-FabricDatasetRefresh -DatasetID [] +Invoke-FabricDatasetRefresh [-DatasetId] [[-WorkspaceId] ] [[-NotifyOption] ] + [[-Type] ] [[-CommitMode] ] [[-MaxParallelism] ] [[-RetryCount] ] + [[-Timeout] ] [[-EffectiveDate] ] [[-ApplyRefreshPolicy] ] + [[-Objects] ] [-WhatIf] [-Confirm] [] ``` ## ALIASES ## DESCRIPTION -The Invoke-FabricDatasetRefresh function is used to refresh a PowerBI dataset. -It first checks if the dataset is refreshable. -If it is not, it writes an error. -If it is, it invokes a PowerBI REST method to refresh the dataset. -The URL for the request is constructed using the provided dataset ID. +Calls the Power BI REST API to trigger an on-demand refresh for a specified dataset. +When `WorkspaceId` is supplied the request targets the dataset inside a specific workspace +(`groups/{groupId}/datasets/{datasetId}/refreshes`); otherwise it targets the dataset +in My Workspace (`datasets/{datasetId}/refreshes`). + +Providing any parameter beyond `NotifyOption` triggers an enhanced refresh (requires +Premium or Fabric capacity). +Shared capacity supports only `NotifyOption` and is +limited to 8 refreshes per day. ## EXAMPLES ### EXAMPLE 1 -Invoke-FabricDatasetRefresh -DatasetID "12345678-1234-1234-1234-123456789012" +Triggers a simple refresh of a dataset in My Workspace. + +```powershell +Invoke-FabricDatasetRefresh -DatasetId "12345678-90ab-cdef-1234-567890abcdef" +``` + +### EXAMPLE 2 + +Triggers a full refresh of a dataset in a specific workspace with email notification on failure. + +```powershell +Invoke-FabricDatasetRefresh ` + -DatasetId "12345678-90ab-cdef-1234-567890abcdef" ` + -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" ` + -Type Full ` + -NotifyOption MailOnFailure +``` + +### EXAMPLE 3 + +Triggers an enhanced refresh targeting specific tables only. -This command invokes a refresh of the dataset with the ID "12345678-1234-1234-1234-123456789012" +```powershell +Invoke-FabricDatasetRefresh ` + -DatasetId "12345678-90ab-cdef-1234-567890abcdef" ` + -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" ` + -Objects @(@{ table = 'Sales' }, @{ table = 'Date' }) ` + -CommitMode PartialBatch +``` ## PARAMETERS -### -DatasetID +### -ApplyRefreshPolicy -A mandatory parameter that specifies the dataset ID. +(Optional) Whether to apply the configured incremental refresh policy. +Triggers an enhanced refresh when specified. ```yaml -Type: System.Guid +Type: System.Boolean +DefaultValue: False +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 9 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -CommitMode + +(Optional) Determines whether objects are committed in batches or only when complete. +Valid values: Transactional, PartialBatch. +Triggers an enhanced refresh when specified. + +```yaml +Type: System.String DefaultValue: '' SupportsWildcards: false Aliases: [] ParameterSets: -- Name: DatasetId +- Name: (All) + Position: 4 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -DatasetId + +(Mandatory) The unique identifier of the dataset to refresh. + +```yaml +Type: System.Guid +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 0 IsRequired: true ValueFromPipeline: false ValueFromPipelineByPropertyName: false @@ -64,6 +164,214 @@ AcceptedValues: [] HelpMessage: '' ``` +### -EffectiveDate + +(Optional) If an incremental refresh policy is applied, overrides the current date used +to determine the rolling window period. +Triggers an enhanced refresh when specified. + +```yaml +Type: System.DateTime +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 8 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -MaxParallelism + +(Optional) The maximum number of threads on which to run parallel processing commands. +Triggers an enhanced refresh when specified. + +```yaml +Type: System.Int32 +DefaultValue: 0 +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 5 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -NotifyOption + +(Optional) Mail notification preference for the refresh. +Valid values: NoNotification, MailOnFailure, MailOnCompletion. +Defaults to NoNotification. +Not applicable to enhanced refreshes or service principal operations. + +```yaml +Type: System.String +DefaultValue: NoNotification +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 2 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -Objects + +(Optional) An array of hashtables specifying specific tables and/or partitions to process. +Each entry should contain 'table' and optionally 'partition' keys. +Triggers an enhanced refresh when specified. + +Example: @(@{ table = 'Sales' }, @{ table = 'Date'; partition = 'Date-2024' }) + +```yaml +Type: System.Collections.Hashtable[] +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 10 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -RetryCount + +(Optional) The number of times the operation is retried before failing. +Triggers an enhanced refresh when specified. + +```yaml +Type: System.Int32 +DefaultValue: 0 +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 6 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -Timeout + +(Optional) The timeout per individual refresh attempt, in HH:MM:SS format (max 24 hours +total including retries). +Defaults to 5 hours. +Triggers an enhanced refresh when specified. + +```yaml +Type: System.String +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 7 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -Type + +(Optional) The type of processing to perform. +Valid values: Full, ClearValues, Calculate, DataOnly, Automatic, Defragment. +Triggers an enhanced refresh when specified. + +```yaml +Type: System.String +DefaultValue: '' +SupportsWildcards: false +Aliases: [] +ParameterSets: +- Name: (All) + Position: 3 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -WhatIf + +Runs the command in a mode that only reports what would happen without performing the actions. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + +### -WorkspaceId + +(Optional) The unique identifier of the workspace that contains the dataset. +When omitted, the My Workspace endpoint is used. + +```yaml +Type: System.Guid +DefaultValue: '' +SupportsWildcards: false +Aliases: +- GroupId +ParameterSets: +- Name: (All) + Position: 1 + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, @@ -77,12 +385,12 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## NOTES -Alias: Invoke-FabDatasetRefresh - -Author: Ioana Bouariu - +- Requires a valid Power BI / Fabric token (call `Connect-FabricAccount` first). +- Calls `Confirm-TokenState` to ensure token validity before making the API request. +- The API responds with 202 Accepted; the refresh runs asynchronously in the background. +- Use `Get-FabricDatasetRefreshHistory` to monitor refresh status. -Define parameters for the workspace ID and dataset ID. +Author: Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/New-FabricLakehouse.md b/docs/en-US/New-FabricLakehouse.md index 1ddfb0fc..9b2fd8e1 100644 --- a/docs/en-US/New-FabricLakehouse.md +++ b/docs/en-US/New-FabricLakehouse.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: New-FabricLakehouse --- @@ -190,7 +190,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/New-FabricNotebook.md b/docs/en-US/New-FabricNotebook.md index 5efae1a8..e100195b 100644 --- a/docs/en-US/New-FabricNotebook.md +++ b/docs/en-US/New-FabricNotebook.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: New-FabricNotebook --- @@ -211,7 +211,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/New-FabricNotebookNEW.md b/docs/en-US/New-FabricNotebookNEW.md deleted file mode 100644 index 782aa9f5..00000000 --- a/docs/en-US/New-FabricNotebookNEW.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -document type: cmdlet -external help file: FabricTools-Help.xml -HelpUri: '' -Locale: en-US -Module Name: FabricTools -ms.date: 04/01/2026 -PlatyPS schema version: 2024-05-01 -title: New-FabricNotebookNEW ---- - -# New-FabricNotebookNEW - -## SYNOPSIS - -Creates a new notebook in a specified Microsoft Fabric workspace. - -## SYNTAX - -### __AllParameterSets - -``` -New-FabricNotebookNEW [-WorkspaceId] [-NotebookName] - [[-NotebookDescription] ] [[-NotebookPathDefinition] ] [-WhatIf] [-Confirm] - [] -``` - -## ALIASES - -## 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. - -## EXAMPLES - -### EXAMPLE 1 - -```powershell -Add-FabricNotebook -WorkspaceId "workspace-12345" -NotebookName "New Notebook" -NotebookPathDefinition "C:\notebooks\example.ipynb" -``` - -## PARAMETERS - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -NotebookDescription - -An optional description for the notebook. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 2 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -NotebookName - -The name of the notebook to be created. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -NotebookPathDefinition - -An optional path to the notebook definition file (e.g., .ipynb file) to upload. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 3 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Runs the command in a mode that only reports what would happen without performing the actions. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WorkspaceId - -The unique identifier of the workspace where the notebook will be created. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: true - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - -## RELATED LINKS - -{{ Fill in the related links here }} - diff --git a/docs/en-US/New-FabricRecoveryPoint.md b/docs/en-US/New-FabricRecoveryPoint.md deleted file mode 100644 index 5d308004..00000000 --- a/docs/en-US/New-FabricRecoveryPoint.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -document type: cmdlet -external help file: FabricTools-Help.xml -HelpUri: '' -Locale: en-US -Module Name: FabricTools -ms.date: 04/01/2026 -PlatyPS schema version: 2024-05-01 -title: New-FabricRecoveryPoint ---- - -# New-FabricRecoveryPoint - -## SYNOPSIS - -Create a recovery point for a Fabric data warehouse - -## SYNTAX - -### __AllParameterSets - -``` -New-FabricRecoveryPoint [[-WorkspaceGUID] ] [[-DataWarehouseGUID] ] - [[-BaseUrl] ] [-WhatIf] [-Confirm] [] -``` - -## ALIASES - -## DESCRIPTION - -Create a recovery point for a Fabric data warehouse - -## EXAMPLES - -### EXAMPLE 1 - -New-FabricRecoveryPoint - -Create a new recovery point for the data warehouse specified in the configuration. - -### EXAMPLE 2 - -Create a new recovery point for the specified data warehouse, in the specified workspace. - -```powershell -New-FabricRecoveryPoint -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -``` - -## PARAMETERS - -### -BaseUrl - -Defaults to api.powerbi.com - -```yaml -Type: System.String -DefaultValue: api.powerbi.com -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 2 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -DataWarehouseGUID - -The GUID for the data warehouse which we want to retrieve restore points for. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Runs the command in a mode that only reports what would happen without performing the actions. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WorkspaceGUID - -This is the workspace GUID in which the data warehouse resides. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -Author: Jess Pomfret - -## RELATED LINKS - -{{ Fill in the related links here }} - diff --git a/docs/en-US/Remove-FabricLakehouse.md b/docs/en-US/Remove-FabricLakehouse.md index 686eddc8..426ecf30 100644 --- a/docs/en-US/Remove-FabricLakehouse.md +++ b/docs/en-US/Remove-FabricLakehouse.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Remove-FabricLakehouse --- @@ -144,7 +144,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Remove-FabricNotebook.md b/docs/en-US/Remove-FabricNotebook.md index 375a63fe..c13236a7 100644 --- a/docs/en-US/Remove-FabricNotebook.md +++ b/docs/en-US/Remove-FabricNotebook.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Remove-FabricNotebook --- @@ -144,7 +144,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Remove-FabricRecoveryPoint.md b/docs/en-US/Remove-FabricRecoveryPoint.md deleted file mode 100644 index 154a4e1c..00000000 --- a/docs/en-US/Remove-FabricRecoveryPoint.md +++ /dev/null @@ -1,200 +0,0 @@ ---- -document type: cmdlet -external help file: FabricTools-Help.xml -HelpUri: '' -Locale: en-US -Module Name: FabricTools -ms.date: 04/01/2026 -PlatyPS schema version: 2024-05-01 -title: Remove-FabricRecoveryPoint ---- - -# Remove-FabricRecoveryPoint - -## SYNOPSIS - -Remove a selected Fabric Recovery Point. - -## SYNTAX - -### __AllParameterSets - -``` -Remove-FabricRecoveryPoint [[-CreateTime] ] [[-WorkspaceGUID] ] - [[-DataWarehouseGUID] ] [[-BaseUrl] ] [-WhatIf] [-Confirm] [] -``` - -## ALIASES - -## DESCRIPTION - -Remove a selected Fabric Recovery Point. - -## EXAMPLES - -### EXAMPLE 1 - -Remove a specific restore point from a Fabric Data Warehouse that has been set using Set-FabricConfig. - -```powershell -Remove-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -``` - -### EXAMPLE 2 - -Remove a specific restore point from a Fabric Data Warehouse, specifying the workspace and data warehouse GUIDs. - -```powershell -Remove-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -``` - -## PARAMETERS - -### -BaseUrl - -Defaults to api.powerbi.com - -```yaml -Type: System.String -DefaultValue: api.powerbi.com -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 3 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -CreateTime - -The specific unique time of the restore point to remove. -Get this from Get-FabricRecoveryPoint. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -DataWarehouseGUID - -The GUID for the data warehouse which we want to retrieve restore points for. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 2 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Runs the command in a mode that only reports what would happen without performing the actions. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WorkspaceGUID - -This is the workspace GUID in which the data warehouse resides. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -Author: Jess Pomfret - -## RELATED LINKS - -{{ Fill in the related links here }} - diff --git a/docs/en-US/Restore-FabricRecoveryPoint.md b/docs/en-US/Restore-FabricRecoveryPoint.md deleted file mode 100644 index 14c93a03..00000000 --- a/docs/en-US/Restore-FabricRecoveryPoint.md +++ /dev/null @@ -1,222 +0,0 @@ ---- -document type: cmdlet -external help file: FabricTools-Help.xml -HelpUri: '' -Locale: en-US -Module Name: FabricTools -ms.date: 04/01/2026 -PlatyPS schema version: 2024-05-01 -title: Restore-FabricRecoveryPoint ---- - -# Restore-FabricRecoveryPoint - -## SYNOPSIS - -Restore a Fabric data warehouse to a specified restore pont. - -## SYNTAX - -### __AllParameterSets - -``` -Restore-FabricRecoveryPoint [[-CreateTime] ] [[-WorkspaceGUID] ] - [[-DataWarehouseGUID] ] [[-BaseUrl] ] [-Wait] [-WhatIf] [-Confirm] - [] -``` - -## ALIASES - -## DESCRIPTION - -Restore a Fabric data warehouse to a specified restore pont. - -## EXAMPLES - -### EXAMPLE 1 - -Restore a Fabric Data Warehouse to a specific restore point that has been set using Set-FabricConfig. - -```powershell -Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -``` - -### EXAMPLE 2 - -Restore a Fabric Data Warehouse to a specific restore point, specifying the workspace and data warehouse GUIDs. - -```powershell -Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -``` - -## PARAMETERS - -### -BaseUrl - -Defaults to api.powerbi.com - -```yaml -Type: System.String -DefaultValue: api.powerbi.com -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 3 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -CreateTime - -The specific unique time of the restore point to remove. -Get this from Get-FabricRecoveryPoint. - -```yaml -Type: System.String -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -DataWarehouseGUID - -The GUID for the data warehouse which we want to retrieve restore points for. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 2 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Wait - -Wait for the restore to complete before returning. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: False -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Runs the command in a mode that only reports what would happen without performing the actions. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WorkspaceGUID - -This is the workspace GUID in which the data warehouse resides. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -Author: Jess Pomfret - -## RELATED LINKS - -{{ Fill in the related links here }} - diff --git a/docs/en-US/Set-FabricConfig.md b/docs/en-US/Set-FabricConfig.md deleted file mode 100644 index 233d62b5..00000000 --- a/docs/en-US/Set-FabricConfig.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -document type: cmdlet -external help file: FabricTools-Help.xml -HelpUri: '' -Locale: en-US -Module Name: FabricTools -ms.date: 04/01/2026 -PlatyPS schema version: 2024-05-01 -title: Set-FabricConfig ---- - -# Set-FabricConfig - -## SYNOPSIS - -Register the configuration for use with all functions in the FabricTools module. - -## SYNTAX - -### __AllParameterSets - -``` -Set-FabricConfig [[-WorkspaceGUID] ] [[-DataWarehouseGUID] ] [[-BaseUrl] ] - [-SkipPersist] [-WhatIf] [-Confirm] [] -``` - -## ALIASES - -## DESCRIPTION - -Register the configuration for use with all functions in the FabricTools module. - -## EXAMPLES - -### EXAMPLE 1 - -Registers the specified Fabric Data Warehouse configuration for use with all functions in the FabricTools module. - -```powershell -Set-FabricConfig -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -``` - -### EXAMPLE 2 - -Registers the specified Fabric Data Warehouse configuration for use with all functions in the FabricTools module, but does not persist the values. - -```powershell -Set-FabricConfig -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -SkipPersist -``` - -## PARAMETERS - -### -BaseUrl - -Defaults to api.powerbi.com - -```yaml -Type: System.Object -DefaultValue: api.powerbi.com -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 2 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -Confirm - -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- cf -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -DataWarehouseGUID - -The GUID for the Data Warehouse which we want to retrieve restore points for. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 1 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -SkipPersist - -If set, the configuration will not be persisted to the registry. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: False -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WhatIf - -Runs the command in a mode that only reports what would happen without performing the actions. - -```yaml -Type: System.Management.Automation.SwitchParameter -DefaultValue: '' -SupportsWildcards: false -Aliases: -- wi -ParameterSets: -- Name: (All) - Position: Named - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### -WorkspaceGUID - -This is the workspace GUID in which the Data Warehouse resides. - -```yaml -Type: System.Guid -DefaultValue: '' -SupportsWildcards: false -Aliases: [] -ParameterSets: -- Name: (All) - Position: 0 - IsRequired: false - ValueFromPipeline: false - ValueFromPipelineByPropertyName: false - ValueFromRemainingArguments: false -DontShow: false -AcceptedValues: [] -HelpMessage: '' -``` - -### CommonParameters - -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, --InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable, --ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see -[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - -## INPUTS - -## OUTPUTS - -## NOTES - -Author: Jess Pomfret - -## RELATED LINKS - -{{ Fill in the related links here }} - diff --git a/docs/en-US/Start-FabricLakehouseTableMaintenance.md b/docs/en-US/Start-FabricLakehouseTableMaintenance.md index 02fc567c..83a23203 100644 --- a/docs/en-US/Start-FabricLakehouseTableMaintenance.md +++ b/docs/en-US/Start-FabricLakehouseTableMaintenance.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Start-FabricLakehouseTableMaintenance --- @@ -319,7 +319,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - The function uses the `Get-FabricLongRunningOperation` function to check the status of long-running operations. - The function uses the `Invoke-RestMethod` cmdlet to make API requests. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Update-FabricLakehouse.md b/docs/en-US/Update-FabricLakehouse.md index e4cfacd6..adb3d2f8 100644 --- a/docs/en-US/Update-FabricLakehouse.md +++ b/docs/en-US/Update-FabricLakehouse.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Update-FabricLakehouse --- @@ -194,7 +194,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Update-FabricNotebook.md b/docs/en-US/Update-FabricNotebook.md index be4a4303..b386ab7c 100644 --- a/docs/en-US/Update-FabricNotebook.md +++ b/docs/en-US/Update-FabricNotebook.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Update-FabricNotebook --- @@ -194,7 +194,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Update-FabricNotebookDefinition.md b/docs/en-US/Update-FabricNotebookDefinition.md index 12be7006..12ce547a 100644 --- a/docs/en-US/Update-FabricNotebookDefinition.md +++ b/docs/en-US/Update-FabricNotebookDefinition.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Update-FabricNotebookDefinition --- @@ -200,7 +200,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable - 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 +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/docs/en-US/Write-FabricLakehouseTableData.md b/docs/en-US/Write-FabricLakehouseTableData.md index 2f26836f..64cab6d5 100644 --- a/docs/en-US/Write-FabricLakehouseTableData.md +++ b/docs/en-US/Write-FabricLakehouseTableData.md @@ -4,7 +4,7 @@ external help file: FabricTools-Help.xml HelpUri: '' Locale: en-US Module Name: FabricTools -ms.date: 04/01/2026 +ms.date: 04/08/2026 PlatyPS schema version: 2024-05-01 title: Write-FabricLakehouseTableData --- @@ -322,7 +322,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## NOTES -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski ## RELATED LINKS diff --git a/helper/GetFunctionList.ps1 b/helper/GetFunctionList.ps1 index e74ed360..84dbe591 100644 --- a/helper/GetFunctionList.ps1 +++ b/helper/GetFunctionList.ps1 @@ -1,10 +1,10 @@ -$path = ".\source\public" +$path = ".\src\public" $op = Get-ChildItem -Path $path -Recurse -Filter *.ps1 | Select-Object -ExpandProperty Name | Sort-Object $op | Out-File '.\output\FunctionList-main-public.txt' # Author Table # This script generates a table of PowerShell script authors from the specified directory. -$path = ".\source\public" +$path = ".\src\public" $op = Get-ChildItem -Path $path -Recurse -Filter *.ps1 $authorTable = @{} $op | ForEach-Object { diff --git a/helper/Update-ReadmeDescriptions.ps1 b/helper/Update-ReadmeDescriptions.ps1 index 5c952bdb..0f1732e5 100644 --- a/helper/Update-ReadmeDescriptions.ps1 +++ b/helper/Update-ReadmeDescriptions.ps1 @@ -5,7 +5,7 @@ Updates the readme.md file with actual function descriptions from PowerShell function files. .DESCRIPTION - This script scans all PowerShell function files in the source/Public directory and its subdirectories, + This script scans all PowerShell function files in the src/Public directory and its subdirectories, extracts the .DESCRIPTION from each function's comment-based help, and replaces the placeholders in the documentation/readme.md file with the actual descriptions. @@ -13,7 +13,7 @@ Path to the readme.md file. Defaults to "documentation/readme.md". .PARAMETER PublicPath - Path to the Public directory containing function files. Defaults to "source/Public". + Path to the Public directory containing function files. Defaults to "src/Public". .EXAMPLE .\Update-ReadmeDescriptions.ps1 @@ -28,7 +28,7 @@ param( [string]$ReadmePath = "documentation/readme.md", - [string]$PublicPath = "source/Public", + [string]$PublicPath = "src/Public", [switch]$Backup = $true ) diff --git a/helper/build-and-test.ps1 b/helper/build-and-test.ps1 index b061d200..4e83f230 100644 --- a/helper/build-and-test.ps1 +++ b/helper/build-and-test.ps1 @@ -12,16 +12,41 @@ Find-Module Microsoft.PowerShell.PSResourceGet Remove-Module -Name FabricTools -ErrorAction SilentlyContinue ./build.ps1 -Tasks build -ipmo .\output\module\FabricTools\0.0.1\FabricTools.psd1 +Import-Module .\output\module\FabricTools\0.0.1\FabricTools.psd1 Get-Module Fab* -# Invoke-ScriptAnalyzer -Path .\source\Public\** +# Invoke-ScriptAnalyzer -Path .\src\Public\** - -$tests = Invoke-Pester .\tests\ -PassThru +## Unit Tests +#$tests = Invoke-Pester .\tests\ -Tag UnitTests -PassThru +$tests = Invoke-Pester .\tests\Unit\ -PassThru $tests.Tests | where Result -eq 'Failed' | Measure-Object | Select-Object -ExpandProperty Count $tests.Tests | where Result -eq 'Failed' | ft -Property ExpandedName, ErrorRecord $tests.Tests | where Result -eq 'Failed' | ft -Property Path, Result, ErrorRecord -AutoSize $e = $tests.Tests | where Result -eq 'Failed' | Select-Object -Last 1 $e.ErrorRecord + +## QA +$tests = Invoke-Pester .\tests\QA -PassThru +$tests.Tests | where Result -eq 'Failed' | ft -Property ExpandedName, ErrorRecord + + +## Integration Tests +Connect-FabricAccount -Debug +$tests = Invoke-Pester .\tests\Integration -PassThru +$tests.Tests | where Result -eq 'Failed' | ft -Property Path, Result, ErrorRecord -AutoSize + + + +Invoke-Pester .\tests\Integration\Notebook* -PassThru + + +Get-FabricDataset +Get-FabricDataset -DatasetName 'sampledwh' +Get-FabricDataset -GroupId '653b4281-c1d1-4307-a8c9-cc18c0b0b8ff' + +Get-FabricDataset -DatasetName 'sampledwh' | Get-FabricDatasetRefreshHistory +Get-FabricDatasetRefreshHistory -DatasetId e1483950-dce9-414c-be60-8d4e66c37e2e + +Get-FabricWorkspace -WorkspaceId '653b4281-c1d1-4307-a8c9-cc18c0b0b8ff' diff --git a/helper/build.ps1 b/helper/build.ps1 index 0151dd69..f4877951 100644 --- a/helper/build.ps1 +++ b/helper/build.ps1 @@ -1,6 +1,6 @@ Remove-Module -Name FabricTools -ErrorAction SilentlyContinue ./build.ps1 -Tasks build -ipmo .\output\module\FabricTools\0.0.1\FabricTools.psd1 +Import-Module .\output\module\FabricTools\0.0.1\FabricTools.psd1 Get-Module FabricTools Write-Host "Connecting to Fabric Account..." -ForegroundColor Cyan diff --git a/helper/integration-tests.ps1 b/helper/integration-tests.ps1 new file mode 100644 index 00000000..96de31cb --- /dev/null +++ b/helper/integration-tests.ps1 @@ -0,0 +1,3 @@ +Connect-FabricAccount + +Invoke-Pester -Path "tests/Integration/" -Tag "Integration" -Output Detailed diff --git a/helper/try-catch.ps1 b/helper/try-catch.ps1 new file mode 100644 index 00000000..b016e1fa --- /dev/null +++ b/helper/try-catch.ps1 @@ -0,0 +1,11 @@ + +# This script checks for the presence of try/catch blocks in .ps1 files under src/Public and lists those that do not have try/catch. + +$all = Get-ChildItem -Path ".\src\Public\*\*.ps1" -Recurse -Filter "*.ps1" +$withTryCatch = $all | Where-Object { Select-String -Path $_.FullName -Pattern '\btry\b' -Quiet } +$withoutTryCatch = $all | Where-Object { -not (Select-String -Path $_.FullName -Pattern '\btry\b' -Quiet) } + +Write-Host "Without try/catch: $($withoutTryCatch.Count) / $($all.Count)" -ForegroundColor Cyan +$withoutTryCatch | ForEach-Object { + $_.FullName.Replace((Resolve-Path ".\src\Public").Path + "\", "") +} diff --git a/source/Private/Get-FabricUri.ps1 b/source/Private/Get-FabricUri.ps1 deleted file mode 100644 index 1f6923a1..00000000 --- a/source/Private/Get-FabricUri.ps1 +++ /dev/null @@ -1,75 +0,0 @@ -<# -.SYNOPSIS -Internal function to connect to Fabric and setup the uri and headers for commands. - -.DESCRIPTION -Internal function to connect to Fabric and setup the uri and headers for commands. - -Requires the Workspace and DataWarehouse GUIDs to connect to. - -.PARAMETER BaseUrl -Defaults to api.powerbi.com - -.PARAMETER WorkspaceGUID -This is the workspace GUID in which the data warehouse resides. - -.PARAMETER DataWarehouseGUID -The GUID for the data warehouse which we want to retrieve restore points for. - -.PARAMETER BatchId -The BatchId to use for the request. If this is set then the batches endpoint will be used. - -.EXAMPLE -Get-FabricUri -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' - -Connects to the specified Fabric Data Warehouse and sets up the headers and uri for future commands. - -.EXAMPLE -Get-FabricUri -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -BatchId 'GUID-GUID-GUID-GUID' - -Connects to the specified Fabric Data Warehouse and sets up the headers and uri for checking the progress of an operation with a specific batchId. - -#> -function Get-FabricUri { - param ( - $BaseUrl = 'api.powerbi.com', - [parameter(Mandatory)] - [guid]$WorkspaceGUID, - [parameter(Mandatory)] - [guid]$DataWarehouseGUID, - - [guid]$BatchId - ) - - try { - $headers = Get-PowerBIAccessToken - } catch { - try { - Stop-PSFFunction -Message ('Not able to get a token - execute Connect-PowerBIServiceAccount manually first') -EnableException - # Write-PSFMessage -Level Warning -Message ('Not able to get a token - will execute Connect-PowerBIServiceAccount') - #TODO: This doesn't work the first time - is it waiting for response? - # $conn = Connect-PowerBIServiceAccount - # if($conn) { - # Write-PSFMessage -Level Info -Message ('Successfully connected to PowerBI') - # } - } catch { - throw 'Not able to get a token - manually try and run Connect-PowerBIServiceAccount' - } - } - - if($BatchId) { - $Uri = ('https://{0}/v1.0/myorg/groups/{1}/datawarehouses/{2}/batches/{3}' -f $baseurl, $workspaceGUID, $dataWarehouseGUID, $BatchId) - $method = 'Get' - } else { - $Uri = ('https://{0}/v1.0/myorg/groups/{1}/datawarehouses/{2}/' -f $baseurl, $workspaceGUID, $dataWarehouseGUID) - $method = 'Post' - } - - return @{ - Uri = $Uri - Headers = $headers - Method = $method - ContentType = 'application/json' - } - #TODO: Change this to be a saved config property? -} diff --git a/source/Public/Capacity/Get-FabricCapacityRefreshables.ps1 b/source/Public/Capacity/Get-FabricCapacityRefreshables.ps1 deleted file mode 100644 index 98379f1e..00000000 --- a/source/Public/Capacity/Get-FabricCapacityRefreshables.ps1 +++ /dev/null @@ -1,38 +0,0 @@ -function Get-FabricCapacityRefreshables { - <# -.SYNOPSIS -Retrieves the top refreshable capacities for the tenant. - -.DESCRIPTION -The Get-FabricCapacityRefreshables function retrieves the top refreshable capacities for the tenant. It supports multiple aliases for flexibility. - -.PARAMETER top -The number of top refreshable capacities to retrieve. This is a mandatory parameter. - -.EXAMPLE - This example retrieves the top 5 refreshable capacities for the tenant. - - ```powershell - Get-FabricCapacityRefreshables -top 5 - ``` - -.NOTES -The function retrieves the PowerBI access token and makes a GET request to the PowerBI API to retrieve the top refreshable capacities. It then returns the 'value' property of the response, which contains the capacities. - -Author: Ioana Bouariu - - #> - - # Define a mandatory parameter for the number of top refreshable capacities to retrieve. - Param ( - [Parameter(Mandatory = $false)] - [string]$top = 5 - ) - - Confirm-TokenState - - # Make a GET request to the PowerBI API to retrieve the top refreshable capacities. - # The function returns the 'value' property of the response. - $result = Invoke-FabricRestMethod -Method GET -PowerBIApi -Uri "capacities/refreshables?`$top=$top" - $result.value -} diff --git a/source/Public/Config/Set-FabricConfig.ps1 b/source/Public/Config/Set-FabricConfig.ps1 deleted file mode 100644 index 4c06bb91..00000000 --- a/source/Public/Config/Set-FabricConfig.ps1 +++ /dev/null @@ -1,67 +0,0 @@ -function Set-FabricConfig { - <# -.SYNOPSIS -Register the configuration for use with all functions in the FabricTools module. - -.DESCRIPTION -Register the configuration for use with all functions in the FabricTools module. - -.PARAMETER WorkspaceGUID -This is the workspace GUID in which the Data Warehouse resides. - -.PARAMETER DataWarehouseGUID -The GUID for the Data Warehouse which we want to retrieve restore points for. - -.PARAMETER BaseUrl -Defaults to api.powerbi.com - -.PARAMETER SkipPersist -If set, the configuration will not be persisted to the registry. - -.EXAMPLE - Registers the specified Fabric Data Warehouse configuration for use with all functions in the FabricTools module. - - ```powershell - Set-FabricConfig -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' - ``` - -.EXAMPLE - Registers the specified Fabric Data Warehouse configuration for use with all functions in the FabricTools module, but does not persist the values. - - ```powershell - Set-FabricConfig -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' -SkipPersist - ``` - -.NOTES - -Author: Jess Pomfret -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [guid]$WorkspaceGUID, - - [guid]$DataWarehouseGUID, - - $BaseUrl = 'api.powerbi.com', - - [switch]$SkipPersist - ) - - if ($PSCmdlet.ShouldProcess("Setting Fabric Configuration")) { - - if ($BaseUrl) { - Set-PSFConfig -Module 'FabricTools' -Name BaseUrl -Value $BaseUrl - } - if ($WorkspaceGUID) { - Set-PSFConfig -Module 'FabricTools' -Name WorkspaceGUID -Value $WorkspaceGUID - } - if ($DataWarehouseGUID) { - Set-PSFConfig -Module 'FabricTools' -Name DataWarehouseGUID -Value $DataWarehouseGUID - } - - # Register the config values in the registry if skip persist is not set - if (-not $SkipPersist) { - Register-PSFConfig -Module 'FabricTools' -Scope SystemMandatory - } - } -} diff --git a/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentByCapacity.ps1 b/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentByCapacity.ps1 deleted file mode 100644 index ca4ceca6..00000000 --- a/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentByCapacity.ps1 +++ /dev/null @@ -1,105 +0,0 @@ -function Add-FabricDomainWorkspaceAssignmentByCapacity { -<# -.SYNOPSIS -Assigns workspaces to a Fabric domain based on specified capacities. - -.DESCRIPTION -The `Add-FabricDomainWorkspaceAssignmentByCapacity` 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 - Assigns workspaces to the domain with ID "12345" based on the specified capacities. - - ```powershell - Add-FabricDomainWorkspaceAssignmentByCapacity -DomainId "12345" -CapacitiesIds @("capacity1", "capacity2") - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch -#> - [CmdletBinding()] - [Alias("Assign-FabricDomainWorkspaceByCapacity")] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$DomainId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid[]]$CapacitiesIds - ) - - try { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentByPrincipal.ps1 b/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentByPrincipal.ps1 deleted file mode 100644 index eb4afd48..00000000 --- a/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentByPrincipal.ps1 +++ /dev/null @@ -1,111 +0,0 @@ -function Add-FabricDomainWorkspaceAssignmentByPrincipal { -<# -.SYNOPSIS -Assigns workspaces to a domain based on principal IDs in Microsoft Fabric. - -.DESCRIPTION -The `Add-FabricDomainWorkspaceAssignmentByPrincipal` 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 - This example assigns workspaces to a domain using a list of principal IDs and types. - - ```powershell - $PrincipalIds = @( - @{id = "813abb4a-414c-4ac0-9c2c-bd17036fd58c"; type = "User"}, - @{id = "b5b9495c-685a-447a-b4d3-2d8e963e6288"; type = "User"} - ) - - Add-FabricDomainWorkspaceAssignmentByPrincipal -DomainId "12345" -PrincipalIds $PrincipalIds - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch -#> - [CmdletBinding()] - [Alias("Assign-FabricDomainWorkspaceByPrincipal")] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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/source/Public/Domain/Get-FabricDomainWorkspace.ps1 b/source/Public/Domain/Get-FabricDomainWorkspace.ps1 deleted file mode 100644 index f5852758..00000000 --- a/source/Public/Domain/Get-FabricDomainWorkspace.ps1 +++ /dev/null @@ -1,72 +0,0 @@ -function Get-FabricDomainWorkspace { -<# -.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 - Fetches workspaces for the domain with ID "12345". - - ```powershell - Get-FabricDomainWorkspace -DomainId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$DomainId - ) - - try { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 = $_.Exception.Message - Write-Message -Message "Failed to retrieve domain workspaces. Error: $errorDetails" -Level Error - } -} diff --git a/source/Public/Domain/New-FabricDomain.ps1 b/source/Public/Domain/New-FabricDomain.ps1 deleted file mode 100644 index 218753a5..00000000 --- a/source/Public/Domain/New-FabricDomain.ps1 +++ /dev/null @@ -1,135 +0,0 @@ -function New-FabricDomain -{ -<# -.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 - Creates a "Finance" domain under the parent domain with ID "12345". - - ```powershell - Add-FabricDomain -DomainName "Finance" -DomainDescription "Finance data domain" -ParentDomainId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$DomainName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$DomainDescription, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$ParentDomainId - ) - - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - - if ($PSCmdlet.ShouldProcess($DomainName, "Create Domain")) - { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/source/Public/Environment/Get-FabricEnvironment.ps1 b/source/Public/Environment/Get-FabricEnvironment.ps1 deleted file mode 100644 index c4762b41..00000000 --- a/source/Public/Environment/Get-FabricEnvironment.ps1 +++ /dev/null @@ -1,150 +0,0 @@ -function Get-FabricEnvironment { - - <# -.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 EnvironmentId -(Optional) The ID of a specific environment to retrieve. - -.PARAMETER EnvironmentName -(Optional) The name of the specific environment to retrieve. - -.EXAMPLE - Retrieves the "Development" environment from workspace "12345". - - ```powershell - Get-FabricEnvironment -WorkspaceId "12345" -EnvironmentName "Development" - ``` - -.EXAMPLE - Retrieves all environments in workspace "12345". - - ```powershell - Get-FabricEnvironment -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` 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 - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$EnvironmentId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Environment/New-FabricEnvironment.ps1 b/source/Public/Environment/New-FabricEnvironment.ps1 deleted file mode 100644 index ab92d075..00000000 --- a/source/Public/Environment/New-FabricEnvironment.ps1 +++ /dev/null @@ -1,127 +0,0 @@ -function New-FabricEnvironment -{ -<# -.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 - Creates an environment named "DevEnv" in workspace "12345" with the specified description. - - ```powershell - Add-FabricEnvironment -WorkspaceId "12345" -EnvironmentName "DevEnv" -EnvironmentDescription "Development Environment" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$EnvironmentName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$EnvironmentDescription - ) - - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - if ($PSCmdlet.ShouldProcess($EnvironmentName, "Create Environment")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/source/Public/Environment/Publish-FabricEnvironment.ps1 b/source/Public/Environment/Publish-FabricEnvironment.ps1 deleted file mode 100644 index 1ecedccf..00000000 --- a/source/Public/Environment/Publish-FabricEnvironment.ps1 +++ /dev/null @@ -1,95 +0,0 @@ -function Publish-FabricEnvironment { -<# -.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 - Initiates the publishing process for the specified staging environment. - - ```powershell - Publish-FabricEnvironment -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" - ``` - -.NOTES -- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. -- Uses `Confirm-TokenState` to validate the token before making API calls. - -Author: Tiago Balabuch -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$EnvironmentId - ) - - try { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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/source/Public/Eventhouse/Get-FabricEventhouse.ps1 b/source/Public/Eventhouse/Get-FabricEventhouse.ps1 deleted file mode 100644 index c18a0b58..00000000 --- a/source/Public/Eventhouse/Get-FabricEventhouse.ps1 +++ /dev/null @@ -1,176 +0,0 @@ -function Get-FabricEventhouse { - <# - .SYNOPSIS - Retrieves Fabric Eventhouses - - .DESCRIPTION - Retrieves Fabric Eventhouses. Without the EventhouseName or EventhouseID parameter, all Eventhouses are returned. - If you want to retrieve a specific Eventhouse, you can use the EventhouseName or EventhouseID parameter. These - parameters cannot be used together. - - .PARAMETER WorkspaceId - Id of the Fabric Workspace for which the Eventhouses should be retrieved. The value for WorkspaceId is a GUID. - An example of a GUID is '12345678-1234-1234-1234-123456789012'. - - .PARAMETER EventhouseName - The name of the Eventhouse to retrieve. This parameter cannot be used together with EventhouseID. - - .PARAMETER EventhouseId - The Id of the Eventhouse to retrieve. This parameter cannot be used together with EventhouseName. The value for WorkspaceId is a GUID. - An example of a GUID is '12345678-1234-1234-1234-123456789012'. - - .EXAMPLE - This example will give you all Eventhouses in the Workspace. - - ```powershell - Get-FabricEventhouse ` - -WorkspaceId '12345678-1234-1234-1234-123456789012' - ``` - - .EXAMPLE - This example will give you all Information about the Eventhouse with the name 'MyEventhouse'. - - ```powershell - Get-FabricEventhouse ` - -WorkspaceId '12345678-1234-1234-1234-123456789012' ` - -EventhouseName 'MyEventhouse' - ``` - - .EXAMPLE - This example will give you all Information about the Eventhouse with the Id '12345678-1234-1234-1234-123456789012'. - - ```powershell - Get-FabricEventhouse ` - -WorkspaceId '12345678-1234-1234-1234-123456789012' ` - -EventhouseId '12345678-1234-1234-1234-123456789012' - ``` - - .EXAMPLE - This example will give you all Information about the Eventhouse with the Id '12345678-1234-1234-1234-123456789012'. It will also give you verbose output which is useful for debugging. - - ```powershell - Get-FabricEventhouse ` - -WorkspaceId '12345678-1234-1234-1234-123456789012' ` - -EventhouseId '12345678-1234-1234-1234-123456789012' ` - -Verbose - ``` - - .LINK - https://learn.microsoft.com/en-us/rest/api/fabric/eventhouse/items/list-eventhouses?tabs=HTTP - - .NOTES - TODO: Add functionality to list all Eventhouses in the subscription. To do so fetch all workspaces - and then all eventhouses in each workspace. - - Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$EventhouseId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 b/source/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 deleted file mode 100644 index bd0a18df..00000000 --- a/source/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 +++ /dev/null @@ -1,122 +0,0 @@ -function Get-FabricEventhouseDefinition { -<# -.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 - This example retrieves the definition of the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricEventhouseDefinition -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" - ``` - -.EXAMPLE - This example retrieves the definition of the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345" in JSON format. - - ```powershell - Get-FabricEventhouseDefinition -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" -EventhouseFormat "json" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$EventhouseId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$EventhouseFormat - ) - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Eventstream/Get-FabricEventstream.ps1 b/source/Public/Eventstream/Get-FabricEventstream.ps1 deleted file mode 100644 index 585e5fac..00000000 --- a/source/Public/Eventstream/Get-FabricEventstream.ps1 +++ /dev/null @@ -1,156 +0,0 @@ -function Get-FabricEventstream { - - - <# -.SYNOPSIS -Retrieves an Eventstream or a list of Eventstreams from a specified workspace in Microsoft Fabric. - -.DESCRIPTION - Retrieves Fabric Eventstreams. Without the EventstreamName or EventstreamID parameter, all Eventstreams are returned. - If you want to retrieve a specific Eventstream, you can use the EventstreamName or EventstreamID parameter. These - parameters cannot be used together. - -.PARAMETER WorkspaceId -(Mandatory) The ID of the workspace to query Eventstreams. - -.PARAMETER EventstreamName -(Optional) The name of the specific Eventstream to retrieve. - -.PARAMETER EventstreamId - The Id of the Eventstream to retrieve. This parameter cannot be used together with EventstreamName. The value for EventstreamId is a GUID. - An example of a GUID is '12345678-1234-1234-1234-123456789012'. - -.EXAMPLE - Retrieves the "Development" Eventstream from workspace "12345". - - ```powershell - Get-FabricEventstream -WorkspaceId "12345" -EventstreamName "Development" - ``` - -.EXAMPLE - Retrieves all Eventstreams in workspace "12345". - - ```powershell - Get-FabricEventstream -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$EventstreamId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - $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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 b/source/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 deleted file mode 100644 index 585676ad..00000000 --- a/source/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 +++ /dev/null @@ -1,118 +0,0 @@ -function Get-FabricEventstreamDefinition { -<# -.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 - Retrieves the definition of the Eventstream with ID `67890` from the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricEventstreamDefinition -WorkspaceId "12345" -EventstreamId "67890" - ``` - -.EXAMPLE - Retrieves the definitions of all Eventstreams in the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricEventstreamDefinition -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. -- Handles long-running operations asynchronously. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$EventstreamId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$EventstreamFormat - ) - - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Get-SHA256.ps1 b/source/Public/Get-SHA256.ps1 deleted file mode 100644 index bc0f4146..00000000 --- a/source/Public/Get-SHA256.ps1 +++ /dev/null @@ -1,38 +0,0 @@ -function Get-Sha256 ($string) { -<# -.SYNOPSIS -Calculates the SHA256 hash of a string. - -.DESCRIPTION -The Get-Sha256 function calculates the SHA256 hash of a string. - -.PARAMETER string -The string to hash. This is a mandatory parameter. - -.EXAMPLE -Get-Sha256 -string "your-string" - -This example calculates the SHA256 hash of a string. - -.NOTES -The function creates a new SHA256CryptoServiceProvider object, converts the string to a byte array using UTF8 encoding, computes the SHA256 hash of the byte array, converts the hash to a string and removes any hyphens, and returns the resulting hash. - -Author: Ioana Bouariu - -#> - - # Create a new SHA256CryptoServiceProvider object. - $sha256 = New-Object System.Security.Cryptography.SHA256CryptoServiceProvider - - # Convert the string to a byte array using UTF8 encoding. - $bytes = [System.Text.Encoding]::UTF8.GetBytes($string) - - # Compute the SHA256 hash of the byte array. - $hash = $sha256.ComputeHash($bytes) - - # Convert the hash to a string and remove any hyphens. - $result = [System.BitConverter]::ToString($hash) -replace '-' - - # Return the resulting hash. - return $result -} diff --git a/source/Public/Invoke-FabricDatasetRefresh.ps1 b/source/Public/Invoke-FabricDatasetRefresh.ps1 deleted file mode 100644 index 370ee0c5..00000000 --- a/source/Public/Invoke-FabricDatasetRefresh.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -function Invoke-FabricDatasetRefresh { - <# - .SYNOPSIS - This function invokes a refresh of a PowerBI dataset - - .DESCRIPTION - The Invoke-FabricDatasetRefresh function is used to refresh a PowerBI dataset. It first checks if the dataset is refreshable. If it is not, it writes an error. If it is, it invokes a PowerBI REST method to refresh the dataset. The URL for the request is constructed using the provided dataset ID. - - .PARAMETER DatasetID - A mandatory parameter that specifies the dataset ID. - - .EXAMPLE - Invoke-FabricDatasetRefresh -DatasetID "12345678-1234-1234-1234-123456789012" - - This command invokes a refresh of the dataset with the ID "12345678-1234-1234-1234-123456789012" - - .NOTES - Alias: Invoke-FabDatasetRefresh - - Author: Ioana Bouariu - -#> - # Define parameters for the workspace ID and dataset ID. - param( - # Mandatory parameter for the dataset ID - [Parameter(Mandatory = $true, ParameterSetName = "DatasetId")] - [guid]$DatasetID - ) - - Confirm-TokenState - - # Check if the dataset is refreshable - if ((Get-FabricDataset -DatasetId $DatasetID).isrefreshable -eq $false) { - # If the dataset is not refreshable, write an error - Write-Error "Dataset is not refreshable" - } else { - # If the dataset is refreshable, invoke a PowerBI REST method to refresh the dataset - # The URL for the request is constructed using the provided workspace ID and dataset ID. - Invoke-FabricRestMethod -Method POST -PowerBIApi -Uri "datasets/$DatasetID/refreshes" - } -} diff --git a/source/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 b/source/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 deleted file mode 100644 index 0444ed26..00000000 --- a/source/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 +++ /dev/null @@ -1,147 +0,0 @@ -function Get-FabricKQLDashboard { -<# -.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 KQLDashboardId -(Optional) The ID of the specific KQLDashboard to retrieve. - -.PARAMETER KQLDashboardName -(Optional) The name of the specific KQLDashboard to retrieve. - -.EXAMPLE - Retrieves the "Development" KQLDashboard from workspace "12345". .PARAMETER KQLDashboardID The Id of the KQLDashboard to retrieve. This parameter cannot be used together with KQLDashboardName. The value for KQLDashboardID is a GUID. An example of a GUID is '12345678-1234-1234-1234-123456789012'. - - ```powershell - Get-FabricKQLDashboard -WorkspaceId "12345" -KQLDashboardName "Development" - ``` - -.EXAMPLE - Retrieves all KQLDashboards in workspace "12345". - - ```powershell - Get-FabricKQLDashboard -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$KQLDashboardId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 b/source/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 deleted file mode 100644 index 2081a4ec..00000000 --- a/source/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 +++ /dev/null @@ -1,117 +0,0 @@ -function Get-FabricKQLDashboardDefinition { -<# -.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 - Retrieves the definition of the KQLDashboard with ID `67890` from the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricKQLDashboardDefinition -WorkspaceId "12345" -KQLDashboardId "67890" - ``` - -.EXAMPLE - Retrieves the definitions of all KQLDashboards in the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricKQLDashboardDefinition -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. -- Handles long-running operations asynchronously. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$KQLDashboardId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$KQLDashboardFormat - ) - - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/KQL Database/Get-FabricKQLDatabase.ps1 b/source/Public/KQL Database/Get-FabricKQLDatabase.ps1 deleted file mode 100644 index d5d8a30c..00000000 --- a/source/Public/KQL Database/Get-FabricKQLDatabase.ps1 +++ /dev/null @@ -1,146 +0,0 @@ -function Get-FabricKQLDatabase { - <# -.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 KQLDatabaseId -(Optional) The ID of a specific KQLDatabase to retrieve. - -.PARAMETER KQLDatabaseName -(Optional) The name of the specific KQLDatabase to retrieve. - -.EXAMPLE - Retrieves the "Development" KQLDatabase from workspace "12345". - - ```powershell - Get-FabricKQLDatabase -WorkspaceId "12345" -KQLDatabaseName "Development" - ``` - -.EXAMPLE - Retrieves all KQLDatabases in workspace "12345". - - ```powershell - Get-FabricKQLDatabase -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$KQLDatabaseId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 b/source/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 deleted file mode 100644 index 5828dff7..00000000 --- a/source/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 +++ /dev/null @@ -1,125 +0,0 @@ -function Get-FabricKQLDatabaseDefinition { -<# -.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 - Retrieves the definition of the KQLDatabase with ID `67890` from the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricKQLDatabaseDefinition -WorkspaceId "12345" -KQLDatabaseId "67890" - ``` - -.EXAMPLE - Retrieves the definitions of all KQLDatabases in the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricKQLDatabaseDefinition -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. -- Handles long-running operations asynchronously. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$KQLDatabaseId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$KQLDatabaseFormat - ) - - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 b/source/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 deleted file mode 100644 index 076380c6..00000000 --- a/source/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 +++ /dev/null @@ -1,146 +0,0 @@ -function Get-FabricKQLQueryset { - <# -.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 KQLQuerysetId -(Optional) The ID of a specific KQLQueryset to retrieve. - -.PARAMETER KQLQuerysetName -(Optional) The name of the specific KQLQueryset to retrieve. - -.EXAMPLE - Retrieves the "Development" KQLQueryset from workspace "12345". - - ```powershell - Get-FabricKQLQueryset -WorkspaceId "12345" -KQLQuerysetName "Development" - ``` - -.EXAMPLE - Retrieves all KQLQuerysets in workspace "12345". - - ```powershell - Get-FabricKQLQueryset -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$KQLQuerysetId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 b/source/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 deleted file mode 100644 index f14944e5..00000000 --- a/source/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 +++ /dev/null @@ -1,117 +0,0 @@ -function Get-FabricKQLQuerysetDefinition { -<# -.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 - Retrieves the definition of the KQLQueryset with ID `67890` from the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricKQLQuerysetDefinition -WorkspaceId "12345" -KQLQuerysetId "67890" - ``` - -.EXAMPLE - Retrieves the definitions of all KQLQuerysets in the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricKQLQuerysetDefinition -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. -- Handles long-running operations asynchronously. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$KQLQuerysetId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$KQLQuerysetFormat - ) - - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Lakehouse/Get-FabricLakehouse.ps1 b/source/Public/Lakehouse/Get-FabricLakehouse.ps1 deleted file mode 100644 index 69f04291..00000000 --- a/source/Public/Lakehouse/Get-FabricLakehouse.ps1 +++ /dev/null @@ -1,146 +0,0 @@ -function Get-FabricLakehouse { - <# -.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 LakehouseId -(Optional) The ID of a specific Lakehouse to retrieve. - -.PARAMETER LakehouseName -(Optional) The name of the specific Lakehouse to retrieve. - -.EXAMPLE - Retrieves the "Development" Lakehouse from workspace "12345". - - ```powershell - Get-FabricLakehouse -WorkspaceId "12345" -LakehouseName "Development" - ``` - -.EXAMPLE - Retrieves all Lakehouses in workspace "12345". - - ```powershell - Get-FabricLakehouse -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$LakehouseId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Lakehouse/Get-FabricLakehouseTable.ps1 b/source/Public/Lakehouse/Get-FabricLakehouseTable.ps1 deleted file mode 100644 index 284ba68c..00000000 --- a/source/Public/Lakehouse/Get-FabricLakehouseTable.ps1 +++ /dev/null @@ -1,119 +0,0 @@ -function Get-FabricLakehouseTable { - - <# -.SYNOPSIS -Retrieves tables from a specified Lakehouse in a Fabric workspace. - -.DESCRIPTION -This function retrieves tables from a specified Lakehouse in a Fabric workspace. It handles pagination using a continuation token to ensure all data is retrieved. - -.PARAMETER WorkspaceId -The ID of the workspace containing the Lakehouse. - -.PARAMETER LakehouseId -The ID of the Lakehouse from which to retrieve tables. - -.EXAMPLE - This example retrieves all tables from the specified Lakehouse in the specified workspace. - - ```powershell - Get-FabricLakehouseTable -WorkspaceId "your-workspace-id" -LakehouseId "your-lakehouse-id" - ``` - -.NOTES - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - [OutputType([System.Object[]])] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$LakehouseId - ) - - try { - # Step 1: Ensure token validity - Confirm-TokenState - - - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - 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/source/Public/ML Experiment/Get-FabricMLExperiment.ps1 b/source/Public/ML Experiment/Get-FabricMLExperiment.ps1 deleted file mode 100644 index 0ca1ba70..00000000 --- a/source/Public/ML Experiment/Get-FabricMLExperiment.ps1 +++ /dev/null @@ -1,148 +0,0 @@ -function Get-FabricMLExperiment { -<# -.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 - This example retrieves the ML Experiment details for the experiment with ID "experiment-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentId "experiment-67890" - ``` - -.EXAMPLE - This example retrieves the ML Experiment details for the experiment named "My ML Experiment" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentName "My ML Experiment" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$MLExperimentId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/ML Experiment/New-FabricMLExperiment.ps1 b/source/Public/ML Experiment/New-FabricMLExperiment.ps1 deleted file mode 100644 index be98671b..00000000 --- a/source/Public/ML Experiment/New-FabricMLExperiment.ps1 +++ /dev/null @@ -1,136 +0,0 @@ -function New-FabricMLExperiment -{ -<# -.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 - This example creates a new ML Experiment named "New ML Experiment" in the workspace with ID "workspace-12345" with the provided description. - - ```powershell - New-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentName "New ML Experiment" -MLExperimentDescription "Description of the new ML Experiment" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$MLExperimentName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$MLExperimentDescription - ) - - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - if ($PSCmdlet.ShouldProcess($MLExperimentName, "Create ML Experiment")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/source/Public/ML Model/Get-FabricMLModel.ps1 b/source/Public/ML Model/Get-FabricMLModel.ps1 deleted file mode 100644 index 24a1ddf4..00000000 --- a/source/Public/ML Model/Get-FabricMLModel.ps1 +++ /dev/null @@ -1,148 +0,0 @@ -function Get-FabricMLModel { -<# -.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 - This example retrieves the ML Model details for the model with ID "model-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricMLModel -WorkspaceId "workspace-12345" -MLModelId "model-67890" - ``` - -.EXAMPLE - This example retrieves the ML Model details for the model named "My ML Model" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricMLModel -WorkspaceId "workspace-12345" -MLModelName "My ML Model" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$MLModelId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/ML Model/New-FabricMLModel.ps1 b/source/Public/ML Model/New-FabricMLModel.ps1 deleted file mode 100644 index 72b6aced..00000000 --- a/source/Public/ML Model/New-FabricMLModel.ps1 +++ /dev/null @@ -1,136 +0,0 @@ -function New-FabricMLModel -{ -<# -.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 - This example creates a new ML Model named "New ML Model" in the workspace with ID "workspace-12345" with the provided description. - - ```powershell - New-FabricMLModel -WorkspaceId "workspace-12345" -MLModelName "New ML Model" -MLModelDescription "Description of the new ML Model" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$MLModelName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$MLModelDescription - ) - - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - if ($PSCmdlet.ShouldProcess($MLModelName, "Create ML Model")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/source/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 b/source/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 deleted file mode 100644 index 4dd76696..00000000 --- a/source/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 +++ /dev/null @@ -1,149 +0,0 @@ -function Get-FabricMirroredDatabase { - <# -.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 MirroredDatabaseId -(Optional) The ID of a specific MirroredDatabase to retrieve. - -.PARAMETER MirroredDatabaseName -(Optional) The name of the specific MirroredDatabase to retrieve. - -.EXAMPLE - Retrieves the "Development" MirroredDatabase from workspace "12345". - - ```powershell - Get-FabricMirroredDatabase -WorkspaceId "12345" -MirroredDatabaseName "Development" - ``` - -.EXAMPLE - Retrieves all MirroredDatabases in workspace "12345". - - ```powershell - Get-FabricMirroredDatabase -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$MirroredDatabaseId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - $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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 b/source/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 deleted file mode 100644 index 09e835da..00000000 --- a/source/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 +++ /dev/null @@ -1,106 +0,0 @@ -function Get-FabricMirroredDatabaseDefinition { -<# -.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 - Retrieves the definition of the MirroredDatabase with ID `67890` from the workspace with ID `12345`. - - ```powershell - Get-FabricMirroredDatabaseDefinition -WorkspaceId "12345" -MirroredDatabaseId "67890" - ``` - -.EXAMPLE - Retrieves the definitions of all MirroredDatabases in the workspace with ID `12345`. - - ```powershell - Get-FabricMirroredDatabaseDefinition -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. -- Handles long-running operations asynchronously. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$MirroredDatabaseId - ) - - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 b/source/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 deleted file mode 100644 index b9cd5d8a..00000000 --- a/source/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 +++ /dev/null @@ -1,115 +0,0 @@ -function Get-FabricMirroredDatabaseTableStatus { - <# - - .SYNOPSIS - Retrieves the status of tables in a mirrored database. - - .DESCRIPTION - Retrieves the status of tables in a mirrored database. The function validates the authentication token, constructs the API endpoint URL, and makes a POST request to retrieve the mirroring status of tables. It handles errors and logs messages at various levels (Debug, Error). - - .PARAMETER WorkspaceId - The ID of the workspace containing the mirrored database. - - .PARAMETER MirroredDatabaseId - The ID of the mirrored database whose table status is to be retrieved. - - .EXAMPLE - This example retrieves the status of tables in a mirrored database with the specified ID in the specified workspace. - - ```powershell - Get-FabricMirroredDatabaseTableStatus -WorkspaceId "your-workspace-id" -MirroredDatabaseId "your-mirrored-database-id" - ``` - - .NOTES - The function retrieves the PowerBI access token and makes a POST request to the PowerBI API to retrieve the status of tables in the specified mirrored database. It then returns the 'value' property of the response, which contains the table statuses. - - Author: Tiago Balabuch - - #> - [CmdletBinding()] - [OutputType([System.Object[]])] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$MirroredDatabaseId - ) - - try { - - # Step 2: Ensure token validity - Confirm-TokenState - - $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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 b/source/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 deleted file mode 100644 index 2b527c88..00000000 --- a/source/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 +++ /dev/null @@ -1,149 +0,0 @@ -function Get-FabricMirroredWarehouse { - <# -.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 MirroredWarehouseId -(Optional) The ID of a specific MirroredWarehouse to retrieve. - -.PARAMETER MirroredWarehouseName -(Optional) The name of the specific MirroredWarehouse to retrieve. - -.EXAMPLE - Retrieves the "Development" MirroredWarehouse from workspace "12345". - - ```powershell - Get-FabricMirroredWarehouse -WorkspaceId "12345" -MirroredWarehouseName "Development" - ``` - -.EXAMPLE - Retrieves all MirroredWarehouses in workspace "12345". - - ```powershell - Get-FabricMirroredWarehouse -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$MirroredWarehouseId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - $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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Notebook/Get-FabricNotebook.ps1 b/source/Public/Notebook/Get-FabricNotebook.ps1 deleted file mode 100644 index 49dd59fd..00000000 --- a/source/Public/Notebook/Get-FabricNotebook.ps1 +++ /dev/null @@ -1,147 +0,0 @@ -function Get-FabricNotebook { - <# -.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 NotebookId -(Optional) The ID of a specific Notebook to retrieve. - -.PARAMETER NotebookName -(Optional) The name of the specific Notebook to retrieve. - -.EXAMPLE - Retrieves the "Development" Notebook from workspace "12345". - - ```powershell - Get-FabricNotebook -WorkspaceId "12345" -NotebookName "Development" - ``` - -.EXAMPLE - Retrieves all Notebooks in workspace "12345". - - ```powershell - Get-FabricNotebook -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$NotebookId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Notebook/Get-FabricNotebookDefinition.ps1 b/source/Public/Notebook/Get-FabricNotebookDefinition.ps1 deleted file mode 100644 index b2cb7184..00000000 --- a/source/Public/Notebook/Get-FabricNotebookDefinition.ps1 +++ /dev/null @@ -1,128 +0,0 @@ -function Get-FabricNotebookDefinition { -<# -.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 - Retrieves the definition of the notebook with ID `67890` from the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricNotebookDefinition -WorkspaceId "12345" -NotebookId "67890" - ``` - -.EXAMPLE - Retrieves the definitions of all notebooks in the workspace with ID `12345` in the `ipynb` format. - - ```powershell - Get-FabricNotebookDefinition -WorkspaceId "12345" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. -- Handles long-running operations asynchronously. - -Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$NotebookId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [ValidateSet('ipynb')] - [string]$NotebookFormat = 'ipynb' - ) - - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Notebook/New-FabricNotebookNEW.ps1 b/source/Public/Notebook/New-FabricNotebookNEW.ps1 deleted file mode 100644 index a5197352..00000000 --- a/source/Public/Notebook/New-FabricNotebookNEW.ps1 +++ /dev/null @@ -1,166 +0,0 @@ -function New-FabricNotebookNEW -{ -<# -.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 - ```powershell - Add-FabricNotebook -WorkspaceId "workspace-12345" -NotebookName "New Notebook" -NotebookPathDefinition "C:\notebooks\example.ipynb" - ``` - - .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$NotebookName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$NotebookDescription, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$NotebookPathDefinition - ) - - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - if ($PSCmdlet.ShouldProcess($NotebookName, "Create Notebook")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/source/Public/Reflex/Get-FabricReflex.ps1 b/source/Public/Reflex/Get-FabricReflex.ps1 deleted file mode 100644 index 5a01928d..00000000 --- a/source/Public/Reflex/Get-FabricReflex.ps1 +++ /dev/null @@ -1,148 +0,0 @@ -function Get-FabricReflex { -<# -.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 - This example retrieves the Reflex details for the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricReflex -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" - ``` - -.EXAMPLE - This example retrieves the Reflex details for the Reflex named "My Reflex" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricReflex -WorkspaceId "workspace-12345" -ReflexName "My Reflex" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$ReflexId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Reflex/Get-FabricReflexDefinition.ps1 b/source/Public/Reflex/Get-FabricReflexDefinition.ps1 deleted file mode 100644 index 93f313d6..00000000 --- a/source/Public/Reflex/Get-FabricReflexDefinition.ps1 +++ /dev/null @@ -1,122 +0,0 @@ -function Get-FabricReflexDefinition { -<# -.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 - This example retrieves the definition of the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricReflexDefinition -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" - ``` - -.EXAMPLE - This example retrieves the definition of the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345" in JSON format. - - ```powershell - Get-FabricReflexDefinition -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" -ReflexFormat "json" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$ReflexId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$ReflexFormat - ) - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Report/Get-FabricReport.ps1 b/source/Public/Report/Get-FabricReport.ps1 deleted file mode 100644 index 54151b71..00000000 --- a/source/Public/Report/Get-FabricReport.ps1 +++ /dev/null @@ -1,148 +0,0 @@ -function Get-FabricReport { -<# -.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 - This example retrieves the Report details for the Report with ID "Report-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricReport -WorkspaceId "workspace-12345" -ReportId "Report-67890" - ``` - -.EXAMPLE - This example retrieves the Report details for the Report named "My Report" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricReport -WorkspaceId "workspace-12345" -ReportName "My Report" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$ReportId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Report/Get-FabricReportDefinition.ps1 b/source/Public/Report/Get-FabricReportDefinition.ps1 deleted file mode 100644 index 8d6d6538..00000000 --- a/source/Public/Report/Get-FabricReportDefinition.ps1 +++ /dev/null @@ -1,122 +0,0 @@ -function Get-FabricReportDefinition { -<# -.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 - This example retrieves the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" - ``` - -.EXAMPLE - This example retrieves the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345" in JSON format. - - ```powershell - Get-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" -ReportFormat "json" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$ReportId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$ReportFormat - ) - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Report/New-FabricReport.ps1 b/source/Public/Report/New-FabricReport.ps1 deleted file mode 100644 index 3f7390a7..00000000 --- a/source/Public/Report/New-FabricReport.ps1 +++ /dev/null @@ -1,158 +0,0 @@ -function New-FabricReport -{ -<# -.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 - An optional path to the folder that contains Report definition files to upload. - - -.EXAMPLE - This example creates a new Report named "New Report" in the workspace with ID "workspace-12345" with the provided description. - - ```powershell - New-FabricReport -WorkspaceId "workspace-12345" -ReportName "New Report" -ReportDescription "Description of the new Report" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$ReportName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$ReportDescription, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$ReportPathDefinition - ) - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - - if ($PSCmdlet.ShouldProcess($ReportName, "Create Report")){ - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - 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/source/Public/Report/Update-FabricReportDefinition.ps1 b/source/Public/Report/Update-FabricReportDefinition.ps1 deleted file mode 100644 index 7f3b51df..00000000 --- a/source/Public/Report/Update-FabricReportDefinition.ps1 +++ /dev/null @@ -1,158 +0,0 @@ -function Update-FabricReportDefinition -{ -<# -.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 - This example updates the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345" using the provided definition file. - - ```powershell - Update-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" -ReportPathDefinition "C:\Path\To\ReportDefinition.json" - ``` - -.NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$ReportId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$ReportPathDefinition - ) - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Report Definition")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/source/Public/Restore Points/Get-FabricRecoveryPoint.ps1 b/source/Public/Restore Points/Get-FabricRecoveryPoint.ps1 deleted file mode 100644 index 048eb3fd..00000000 --- a/source/Public/Restore Points/Get-FabricRecoveryPoint.ps1 +++ /dev/null @@ -1,133 +0,0 @@ -function Get-FabricRecoveryPoint { - <# - .SYNOPSIS - Get a list of Fabric recovery points. - - .DESCRIPTION - Get a list of Fabric recovery points. Results can be filter by date or type. - - .PARAMETER BaseUrl - Defaults to api.powerbi.com - - .PARAMETER WorkspaceGUID - This is the workspace GUID in which the data warehouse resides. - - .PARAMETER DataWarehouseGUID - The GUID for the data warehouse which we want to retrieve restore points for. - - .PARAMETER Since - Filter the results to only include restore points created after this date. - - .PARAMETER Type - Filter the results to only include restore points of this type. - - .PARAMETER CreateTime - The specific unique time of the restore point to remove. Get this from Get-FabricRecoveryPoint. - - .EXAMPLE - Gets all the available recovery points for the specified data warehouse, in the specified workspace. - - ```powershell - Get-FabricRecoveryPoint -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' - ``` - - .NOTES - Based on API calls from this blog post: https://blog.fabric.microsoft.com/en-US/blog/the-art-of-data-warehouse-recovery-within-microsoft-fabric/ - - Author: Jess Pomfret - - #> - param ( - [guid]$WorkspaceGUID, - - [guid]$DataWarehouseGUID, - - [String]$BaseUrl = 'api.powerbi.com', - - [DateTime]$Since, - - [ValidateSet("automatic", "userDefined")] - [string]$Type, - #TODO: accept a list of times - [string]$CreateTime - - ) - - #region handle the config parameters - if(-not $WorkspaceGUID) { - $WorkspaceGUID = Get-PSFConfigValue -FullName FabricTools.WorkspaceGUID - } - - if(-not $DataWarehouseGUID) { - $DataWarehouseGUID = Get-PSFConfigValue -FullName FabricTools.DataWarehouseGUID - } - - if(-not $BaseUrl) { - $BaseUrl = Get-PSFConfigValue -FullName FabricTools.BaseUrl - } - - if (-not $WorkspaceGUID -or -not $DataWarehouseGUID -or -not $BaseUrl) { - Stop-PSFFunction -Message 'WorkspaceGUID, DataWarehouseGUID, and BaseUrl are required parameters. Either set them with Set-FabricConfig or pass them in as parameter values' -EnableException $true - } else { - Write-PSFMessage -Level Verbose -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl) - } - #endregion - - #region setting up the API call - try { - # Get token and setup the uri - $getUriParam = @{ - BaseUrl = $BaseUrl - WorkspaceGUID = $WorkspaceGUID - DataWarehouseGUID = $DataWarehouseGUID - } - $iwr = Get-FabricUri @getUriParam - } catch { - Stop-PSFFunction -Message 'Failed to get Fabric URI - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region call the API - if (-not $iwr) { - Stop-PSFFunction -Message 'No URI received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } else { - - # set the body to list restore points - $command = [PSCustomObject]@{ - Commands = @(@{ - '$type' = 'WarehouseListRestorePointsCommand' - }) - } - - try { - # add the body and invoke - $iwr.Add('Body', ($command | ConvertTo-Json -Compress)) - $content = Invoke-WebRequest @iwr - - if($content) { - # change output to be a PowerShell object and view restore points - $restorePoints = ($content.Content | ConvertFrom-Json).operationInformation.progressDetail.restorePoints - - if($CreateTime) { - $restorePoints = $restorePoints | Select-Object @{l='createTimeWhere';e={get-date($_.createTime) -Format 'yyyy-MM-ddTHH:mm:ssZ'}}, * | Where-Object createTimeWhere -eq $createTime - } - - if($Since) { - $restorePoints = $restorePoints | Where-Object { $_.createTime -gt $Since } - } - - if($Type) { - $restorePoints = $restorePoints | Where-Object { $_.createMode -eq $Type } - } - - $restorePoints | Select-Object @{l='createTime';e={get-date($_.createTime) -Format 'yyyy-MM-ddTHH:mm:ssZ'}}, @{l='friendlyCreateTime';e={$_.createTime}}, label, createMode, type, createdByUserObjectId | Sort-Object createTime - #TODO: default view rather than select\sort? - } else { - Stop-PSFFunction -Message 'No Content received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - } catch { - Stop-PSFFunction -Message 'Issue calling Invoke-WebRequest' -ErrorRecord $_ -EnableException $true - } - } - #endregion -} diff --git a/source/Public/Restore Points/New-FabricRecoveryPoint.ps1 b/source/Public/Restore Points/New-FabricRecoveryPoint.ps1 deleted file mode 100644 index e5c912d7..00000000 --- a/source/Public/Restore Points/New-FabricRecoveryPoint.ps1 +++ /dev/null @@ -1,106 +0,0 @@ -function New-FabricRecoveryPoint { -<# -.SYNOPSIS -Create a recovery point for a Fabric data warehouse - -.DESCRIPTION -Create a recovery point for a Fabric data warehouse - -.PARAMETER BaseUrl -Defaults to api.powerbi.com - -.PARAMETER WorkspaceGUID -This is the workspace GUID in which the data warehouse resides. - -.PARAMETER DataWarehouseGUID -The GUID for the data warehouse which we want to retrieve restore points for. - -.EXAMPLE -PS> New-FabricRecoveryPoint - -Create a new recovery point for the data warehouse specified in the configuration. - -.EXAMPLE - Create a new recovery point for the specified data warehouse, in the specified workspace. - - ```powershell - New-FabricRecoveryPoint -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' - ``` -.NOTES - -Author: Jess Pomfret - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [guid]$WorkspaceGUID, - - [guid]$DataWarehouseGUID, - - [String]$BaseUrl = 'api.powerbi.com' - ) - - #region handle the config parameters - if(-not $WorkspaceGUID) { - $WorkspaceGUID = Get-PSFConfigValue -FullName FabricTools.WorkspaceGUID - } - - if(-not $DataWarehouseGUID) { - $DataWarehouseGUID = Get-PSFConfigValue -FullName FabricTools.DataWarehouseGUID - } - - if(-not $BaseUrl) { - $BaseUrl = Get-PSFConfigValue -FullName FabricTools.BaseUrl - } - - if (-not $WorkspaceGUID -or -not $DataWarehouseGUID -or -not $BaseUrl) { - Stop-PSFFunction -Message 'WorkspaceGUID, DataWarehouseGUID, and BaseUrl are required parameters. Either set them with Set-FabricConfig or pass them in as parameter values' -EnableException $true - } else { - Write-PSFMessage -Level Verbose -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl) - } - #endregion - - if ($PSCmdlet.ShouldProcess("Create a recovery point for a Fabric Data Warehouse")) { - #region setting up the API call - try { - # Get token and setup the uri - $getUriParam = @{ - BaseUrl = $BaseUrl - WorkspaceGUID = $WorkspaceGUID - DataWarehouseGUID = $DataWarehouseGUID - } - $iwr = Get-FabricUri @getUriParam - } catch { - Stop-PSFFunction -Message 'Failed to get Fabric URI - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region call the API - if (-not $iwr) { - Stop-PSFFunction -Message 'No URI received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } else { - $command = [PSCustomObject]@{ - Commands = @(@{ - '$type' = 'WarehouseCreateRestorePointCommand' - }) - } - - try { - # add the body and invoke - $iwr.Add('Body', ($command | ConvertTo-Json -Compress)) - $content = Invoke-WebRequest @iwr - - if($content) { - # change output to be a PowerShell object and view new restore point - #TODO: output - select default view but return more? - ($content.Content | ConvertFrom-Json) | Select-Object progressState,@{l='type';e={$_.operationInformation.progressDetail.restorePoint.type}},@{l='createTime';e={get-date($_.operationInformation.progressDetail.restorePoint.createTime) -format 'yyyy-MM-ddTHH:mm:ssZ'}},@{l='friendlyCreateTime';e={$_.operationInformation.progressDetail.restorePoint.createTime}}, @{l='label';e={$_.operationInformation.progressDetail.restorePoint.label}}, @{l='createMode';e={$_.operationInformation.progressDetail.restorePoint.createMode}}, @{l='description';e={$_.operationInformation.progressDetail.restorePoint.description}}, @{l='createdByUserObjectId';e={$_.operationInformation.progressDetail.restorePoint.createdByUserObjectId}}, @{l='lastModifiedByUserObjectId';e={$_.operationInformation.progressDetail.restorePoint.lastModifiedByUserObjectId}}, @{l='lastModifiedTime';e={$_.operationInformation.progressDetail.restorePoint.lastModifiedTime}} - } else { - Stop-PSFFunction -Message 'No Content received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - } catch { - Stop-PSFFunction -Message 'Issue calling Invoke-WebRequest' -ErrorRecord $_ -EnableException $true - } - } - #endregion - } -} diff --git a/source/Public/Restore Points/Remove-FabricRecoveryPoint.ps1 b/source/Public/Restore Points/Remove-FabricRecoveryPoint.ps1 deleted file mode 100644 index db8795ac..00000000 --- a/source/Public/Restore Points/Remove-FabricRecoveryPoint.ps1 +++ /dev/null @@ -1,157 +0,0 @@ -function Remove-FabricRecoveryPoint { -<# -.SYNOPSIS -Remove a selected Fabric Recovery Point. - -.DESCRIPTION -Remove a selected Fabric Recovery Point. - -.PARAMETER CreateTime -The specific unique time of the restore point to remove. Get this from Get-FabricRecoveryPoint. - -.PARAMETER BaseUrl -Defaults to api.powerbi.com - -.PARAMETER WorkspaceGUID -This is the workspace GUID in which the data warehouse resides. - -.PARAMETER DataWarehouseGUID -The GUID for the data warehouse which we want to retrieve restore points for. - -.EXAMPLE - Remove a specific restore point from a Fabric Data Warehouse that has been set using Set-FabricConfig. - - ```powershell - Remove-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' - ``` - -.EXAMPLE - Remove a specific restore point from a Fabric Data Warehouse, specifying the workspace and data warehouse GUIDs. - - ```powershell - Remove-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' - ``` - -.NOTES - -Author: Jess Pomfret - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [string]$CreateTime, - - [guid]$WorkspaceGUID, - - [guid]$DataWarehouseGUID, - - [String]$BaseUrl = 'api.powerbi.com' - - #TODO - implement piping from get? or a way of interactively choosing points to remove - ) - - #region handle the config parameters - if(-not $WorkspaceGUID) { - $WorkspaceGUID = Get-PSFConfigValue -FullName FabricTools.WorkspaceGUID - } - - if(-not $DataWarehouseGUID) { - $DataWarehouseGUID = Get-PSFConfigValue -FullName FabricTools.DataWarehouseGUID - } - - if(-not $BaseUrl) { - $BaseUrl = Get-PSFConfigValue -FullName FabricTools.BaseUrl - } - - if (-not $WorkspaceGUID -or -not $DataWarehouseGUID -or -not $BaseUrl) { - Stop-PSFFunction -Message 'WorkspaceGUID, DataWarehouseGUID, and BaseUrl are required parameters. Either set them with Set-FabricConfig or pass them in as parameter values' -EnableException $true - } else { - Write-PSFMessage -Level Verbose -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl) - } - #endregion - - if ($PSCmdlet.ShouldProcess("Remove recovery point for a Fabric Data Warehouse")) { - #region setting up the API call - try { - # Get token and setup the uri - $getUriParam = @{ - BaseUrl = $BaseUrl - WorkspaceGUID = $WorkspaceGUID - DataWarehouseGUID = $DataWarehouseGUID - } - $iwr = Get-FabricUri @getUriParam - } catch { - Stop-PSFFunction -Message 'Failed to get Fabric URI - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region call the API - if (-not $iwr) { - Stop-PSFFunction -Message 'No URI received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } else { - - # for the API this needs to be an array, even if it's just one item - [string[]]$CreateTimeObj = $CreateTime - - #region check restore point exists - #Get the restore point to make sure it exists - the fabric API doesn't really confirm we deleted anything so we will manually check - $getSplat = @{ - WorkspaceGUID = $WorkspaceGUID - DataWarehouseGUID = $DataWarehouseGUID - BaseUrl = $BaseUrl - CreateTime = $CreateTimeObj - } - - try { - if(Get-FabricRecoveryPoint @getSplat) { - Write-PSFMessage -Level Verbose -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}; CreateTime: {3} - restore point exists' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl, $CreateTime) - } else { - Stop-PSFFunction -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}; CreateTime: {3} - restore point not found!' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl, $CreateTime) -ErrorRecord $_ -EnableException $true - } - } catch { - Stop-PSFFunction -Message 'Issue calling Get-FabricRecoveryPoint to check restore point exists before removal' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region remove the restore point - $command = [PSCustomObject]@{ - commands = @([ordered]@{ - '$type' = 'WarehouseDeleteRestorePointsCommand' - 'RestorePointsToDelete' = $CreateTimeObj - }) - } - - try { - # add the body and invoke - $iwr.Add('Body', ($command | ConvertTo-Json -Compress -Depth 3)) - $content = Invoke-WebRequest @iwr - - if($content) { - # change output to be a PowerShell object and view new restore point - #TODO: output - select default view but return more? - $results = ($content.Content | ConvertFrom-Json) - } else { - Stop-PSFFunction -Message 'No Content received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - } catch { - Stop-PSFFunction -Message 'Issue calling Invoke-WebRequest' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region check restore point exists - try { - #Get the restore point to make sure it exists - the fabric API doesn't really confirm we deleted anything so we will manually check - if(Get-FabricRecoveryPoint @getSplat) { - Stop-PSFFunction -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}; CreateTime: {3} - restore point not was not successfully removed!' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl, $CreateTime) -ErrorRecord $_ -EnableException $true - } else { - Write-PSFMessage -Level Output -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}; CreateTime: {3} - restore point successfully removed' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl, $CreateTime) - $results - } - } catch { - Stop-PSFFunction -Message 'Issue calling Get-FabricRecoveryPoint to check restore point exists before removal' -ErrorRecord $_ -EnableException $true - } - #endregion - } - #endregion - } -} diff --git a/source/Public/Restore Points/Restore-FabricRecoveryPoint.ps1 b/source/Public/Restore Points/Restore-FabricRecoveryPoint.ps1 deleted file mode 100644 index dd3e7f6f..00000000 --- a/source/Public/Restore Points/Restore-FabricRecoveryPoint.ps1 +++ /dev/null @@ -1,187 +0,0 @@ -function Restore-FabricRecoveryPoint { -<# -.SYNOPSIS -Restore a Fabric data warehouse to a specified restore pont. - -.DESCRIPTION -Restore a Fabric data warehouse to a specified restore pont. - -.PARAMETER CreateTime -The specific unique time of the restore point to remove. Get this from Get-FabricRecoveryPoint. - -.PARAMETER BaseUrl -Defaults to api.powerbi.com - -.PARAMETER WorkspaceGUID -This is the workspace GUID in which the data warehouse resides. - -.PARAMETER DataWarehouseGUID -The GUID for the data warehouse which we want to retrieve restore points for. - -.PARAMETER Wait -Wait for the restore to complete before returning. - -.EXAMPLE - Restore a Fabric Data Warehouse to a specific restore point that has been set using Set-FabricConfig. - - ```powershell - Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' - ``` - -.EXAMPLE - Restore a Fabric Data Warehouse to a specific restore point, specifying the workspace and data warehouse GUIDs. - - ```powershell - Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID 'GUID-GUID-GUID-GUID' -DataWarehouseGUID 'GUID-GUID-GUID-GUID' - ``` - -.NOTES - -Author: Jess Pomfret - -#> - [CmdletBinding(SupportsShouldProcess)] - param ( - [string]$CreateTime, - - [guid]$WorkspaceGUID, - - [guid]$DataWarehouseGUID, - - [String]$BaseUrl = 'api.powerbi.com', - - [switch]$Wait - - ) - - #region handle the config parameters - if(-not $WorkspaceGUID) { - $WorkspaceGUID = Get-PSFConfigValue -FullName FabricTools.WorkspaceGUID - } - - if(-not $DataWarehouseGUID) { - $DataWarehouseGUID = Get-PSFConfigValue -FullName FabricTools.DataWarehouseGUID - } - - if(-not $BaseUrl) { - $BaseUrl = Get-PSFConfigValue -FullName FabricTools.BaseUrl - } - - if (-not $WorkspaceGUID -or -not $DataWarehouseGUID -or -not $BaseUrl) { - Stop-PSFFunction -Message 'WorkspaceGUID, DataWarehouseGUID, and BaseUrl are required parameters. Either set them with Set-FabricConfig or pass them in as parameter values' -EnableException $true - } else { - Write-PSFMessage -Level Verbose -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl) - } - #endregion - - if ($PSCmdlet.ShouldProcess("Recover a Fabric Data Warehouse to a restore point")) { - #region setting up the API call - try { - # Get token and setup the uri - $getUriParam = @{ - BaseUrl = $BaseUrl - WorkspaceGUID = $WorkspaceGUID - DataWarehouseGUID = $DataWarehouseGUID - } - $iwr = Get-FabricUri @getUriParam - } catch { - Stop-PSFFunction -Message 'Failed to get Fabric URI - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region call the API - if (-not $iwr) { - Stop-PSFFunction -Message 'No URI received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } else { - - #region check restore point exists - #Get the restore point to make sure it exists before we try and restore to it - $getSplat = @{ - WorkspaceGUID = $WorkspaceGUID - DataWarehouseGUID = $DataWarehouseGUID - BaseUrl = $BaseUrl - CreateTime = $CreateTime - } - - try { - if(Get-FabricRecoveryPoint @getSplat) { - Write-PSFMessage -Level Verbose -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}; CreateTime: {3} - restore point exists' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl, $CreateTime) - } else { - Stop-PSFFunction -Message ('WorkspaceGUID: {0}; DataWarehouseGUID: {1}; BaseUrl: {2}; CreateTime: {3} - restore point not found!' -f $WorkspaceGUID, $DataWarehouseGUID, $BaseUrl, $CreateTime) -ErrorRecord $_ -EnableException $true - } - } catch { - Stop-PSFFunction -Message 'Issue calling Get-FabricRecoveryPoint to check restore point exists before attempting recovery' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region recover to the restore point - # command is now WarehouseRestoreInPlaceCommand and the RestorePoint is the create time of the specific restore point to use - $command = [PSCustomObject]@{ - commands = @([ordered]@{ - '$type' = 'WarehouseRestoreInPlaceCommand' - 'RestorePoint' = $CreateTime - }) - } - - try { - # add the body and invoke - $iwr.Add('Body', ($command | ConvertTo-Json -Compress)) - $content = Invoke-WebRequest @iwr - - if($content) { - #TODO: output - select default view but return more? - $content = ($content.Content | ConvertFrom-Json) - } else { - Stop-PSFFunction -Message 'No Content received from API - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - } catch { - Stop-PSFFunction -Message 'Issue calling Invoke-WebRequest' -ErrorRecord $_ -EnableException $true - } - #endregion - - #region check the progress of the restore - if ($Wait) { - # we need to append batches to the uri - try { - - while($Wait) { - # Get token and setup the uri - $getUriParam = @{ - BaseUrl = $BaseUrl - WorkspaceGUID = $WorkspaceGUID - DataWarehouseGUID = $DataWarehouseGUID - BatchId = $content.batchId - } - $iwr = Get-FabricUri @getUriParam - - $restoreProgress = ((Invoke-WebRequest @iwr).Content | ConvertFrom-Json) - - if($restoreProgress.progressState -eq 'inProgress') { - Write-PSFMessage -Level Output -Message 'Restore in progress' - } elseif ($restoreProgress.progressState -eq 'success') { - Write-PSFMessage -Level Output -Message 'Restore completed successfully' - $restoreProgress | Select-Object progressState, @{l='startDateTimeUtc';e={$_.startTimeStamp }}, @{l='RestorePointCreateTime';e={$CreateTime }} - $wait = $false - break - } else { - Write-PSFMessage -Level Output -Message 'Restore failed' - $restoreProgress | Select-Object progressState, @{l='startDateTimeUtc';e={$_.startTimeStamp }} - $wait = $false - break - } - - # wait a few seconds - Start-Sleep -Seconds 3 - } - } catch { - Stop-PSFFunction -Message 'Failed to get Fabric URI for the batchId - check authentication and parameters.' -ErrorRecord $_ -EnableException $true - } - - } else { - Write-PSFMessage -Level Output -Message 'Restore in progress - use the -Wait parameter to wait for restore to complete' - $content - } - } - #endregion - } -} diff --git a/source/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 b/source/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 deleted file mode 100644 index 9559611a..00000000 --- a/source/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 +++ /dev/null @@ -1,145 +0,0 @@ -function Get-FabricSQLEndpoint { - <# - .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 - ```powershell - Get-FabricSQLEndpoint -WorkspaceId "workspace123" -SQLEndpointId "endpoint456" - ``` - - .EXAMPLE - ```powershell - 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. - - Author: Tiago Balabuch -#> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$SQLEndpointId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Semantic Model/Get-FabricSemanticModel.ps1 b/source/Public/Semantic Model/Get-FabricSemanticModel.ps1 deleted file mode 100644 index 9f0c0d1d..00000000 --- a/source/Public/Semantic Model/Get-FabricSemanticModel.ps1 +++ /dev/null @@ -1,147 +0,0 @@ -function Get-FabricSemanticModel { - <# - .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 - This example retrieves the SemanticModel details for the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" - ``` - - .EXAMPLE - This example retrieves the SemanticModel details for the SemanticModel named "My SemanticModel" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelName "My SemanticModel" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$SemanticModelId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 b/source/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 deleted file mode 100644 index 30051ec4..00000000 --- a/source/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 +++ /dev/null @@ -1,122 +0,0 @@ -function Get-FabricSemanticModelDefinition { - <# - .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 - This example retrieves the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" - ``` - - .EXAMPLE - This example retrieves the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345" in JSON format. - - ```powershell - Get-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" -SemanticModelFormat "json" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$SemanticModelId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [ValidateSet('TMDL', 'TMSL')] - [string]$SemanticModelFormat = "TMDL" - ) - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Semantic Model/New-FabricSemanticModel.ps1 b/source/Public/Semantic Model/New-FabricSemanticModel.ps1 deleted file mode 100644 index cd47ac08..00000000 --- a/source/Public/Semantic Model/New-FabricSemanticModel.ps1 +++ /dev/null @@ -1,152 +0,0 @@ -function New-FabricSemanticModel -{ - <# - .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 - This example creates a new SemanticModel named "New SemanticModel" in the workspace with ID "workspace-12345" with the provided description. - - ```powershell - New-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelName "New SemanticModel" -SemanticModelDescription "Description of the new SemanticModel" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$SemanticModelName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$SemanticModelDescription, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$SemanticModelPathDefinition - ) - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - - if ($PSCmdlet.ShouldProcess("Create SemanticModel", "Creating the SemanticModel '$SemanticModelName' in workspace '$WorkspaceId'.")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - 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/source/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 b/source/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 deleted file mode 100644 index 42f21e82..00000000 --- a/source/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 +++ /dev/null @@ -1,145 +0,0 @@ -function Update-FabricSemanticModelDefinition -{ - <# - .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 - This example updates the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345" using the provided definition file. - - ```powershell - Update-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" -SemanticModelPathDefinition "C:\Path\To\SemanticModelDefinition.json" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$SemanticModelId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$SemanticModelPathDefinition - ) - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 = "{0}?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 - - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update SemanticModel Definition")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/source/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 b/source/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 deleted file mode 100644 index d977a27b..00000000 --- a/source/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 +++ /dev/null @@ -1,147 +0,0 @@ -function Get-FabricSparkJobDefinition { - <# - .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 - This example retrieves the SparkJobDefinition details for the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" - ``` - - .EXAMPLE - This example retrieves the SparkJobDefinition details for the SparkJobDefinition named "My SparkJobDefinition" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionName "My SparkJobDefinition" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$SparkJobDefinitionId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 b/source/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 deleted file mode 100644 index 41c7e72f..00000000 --- a/source/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 +++ /dev/null @@ -1,122 +0,0 @@ -function Get-FabricSparkJobDefinitionDefinition { - <# - .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 - This example retrieves the definition of the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345". - - ```powershell - Get-FabricSparkJobDefinitionDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" - ``` - - .EXAMPLE - This example retrieves the definition of the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345" in JSON format. - - ```powershell - Get-FabricSparkJobDefinitionDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" -SparkJobDefinitionFormat "json" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$SparkJobDefinitionId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [ValidateSet('SparkJobDefinitionV1')] - [string]$SparkJobDefinitionFormat = "SparkJobDefinitionV1" - ) - try { - # Step 2: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 b/source/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 deleted file mode 100644 index f7d7885b..00000000 --- a/source/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 +++ /dev/null @@ -1,123 +0,0 @@ -function Start-FabricSparkJobDefinitionOnDemand -{ - <# - .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 - ```powershell - 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. - - Author: Tiago Balabuch - #> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$SparkJobDefinitionId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [ValidateSet('sparkjob')] - [string]$JobType = "sparkjob", - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [bool]$waitForCompletion = $false - ) - - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Start Spark Job Definition on demand")){ - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - } - 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/source/Public/Spark/Get-FabricSparkSettings.ps1 b/source/Public/Spark/Get-FabricSparkSettings.ps1 deleted file mode 100644 index fa1c6905..00000000 --- a/source/Public/Spark/Get-FabricSparkSettings.ps1 +++ /dev/null @@ -1,111 +0,0 @@ -function Get-FabricSparkSettings { - <# - .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 - This example retrieves the Spark settings for the workspace with ID "workspace-12345". - - ```powershell - Get-FabricSparkSettings -WorkspaceId "workspace-12345" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding()] - [OutputType([System.Object[]])] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$WorkspaceId - ) - - try { - - # Step 2: Ensure token validity - Confirm-TokenState - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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/source/Public/Spark/Update-FabricSparkSettings.ps1 b/source/Public/Spark/Update-FabricSparkSettings.ps1 deleted file mode 100644 index 26539e95..00000000 --- a/source/Public/Spark/Update-FabricSparkSettings.ps1 +++ /dev/null @@ -1,229 +0,0 @@ -function Update-FabricSparkSettings -{ - <# - .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. - - .PARAMETER automaticLogEnabled - Specifies whether automatic logging is enabled for the Spark custom pool. This parameter is optional. - - .PARAMETER notebookInteractiveRunEnabled - Specifies whether notebook interactive run is enabled for the Spark custom pool. This parameter is optional. - - .PARAMETER customizeComputeEnabled - Specifies whether compute customization is enabled for the Spark custom pool. This parameter is optional. - - .PARAMETER defaultPoolName - The name of the default pool for the Spark custom pool. This parameter is optional. - - .PARAMETER defaultPoolType - The type of the default pool for the Spark custom pool. This parameter is optional and must be either 'Workspace' or 'Capacity'. - - .PARAMETER starterPoolMaxNode - The maximum number of nodes for the starter pool in the Spark custom pool. This parameter is optional. - - .PARAMETER starterPoolMaxExecutors - The maximum number of executors for the starter pool in the Spark custom pool. This parameter is optional. - - .PARAMETER EnvironmentName - The name of the environment for the Spark custom pool. This parameter is optional. - - .PARAMETER EnvironmentRuntimeVersion - The runtime version of the environment for the Spark custom pool. This parameter is optional. - - .EXAMPLE - This example updates the Spark custom pool with ID "pool-67890" in the workspace with ID "workspace-12345" with a new name and 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 - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - - #> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [guid]$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 - Confirm-TokenState - - # 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 - - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update SparkSettings")) - { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - - # 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/source/Public/Tenant/Get-FabricWorkspaceTenantSettingOverrides.ps1 b/source/Public/Tenant/Get-FabricWorkspaceTenantSettingOverrides.ps1 deleted file mode 100644 index 42d4b302..00000000 --- a/source/Public/Tenant/Get-FabricWorkspaceTenantSettingOverrides.ps1 +++ /dev/null @@ -1,50 +0,0 @@ -function Get-FabricWorkspaceTenantSettingOverrides { - <# - .SYNOPSIS - Retrieves tenant setting overrides for all workspaces in the Fabric tenant. - - .DESCRIPTION - The `Get-FabricWorkspaceTenantSettingOverrides` function retrieves tenant setting overrides for all workspaces in the Fabric tenant by making a GET request to the appropriate API endpoint. The function validates the authentication token before making the request and handles the response accordingly. - - .EXAMPLE - Returns all workspaces tenant setting overrides. - - ```powershell - Get-FabricWorkspaceTenantSettingOverrides - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding()] - param ( ) - - try { - # Step 1: Validate authentication token before making API requests - Confirm-TokenState - - # Step 2: Construct the API endpoint URL for retrieving workspaces tenant setting overrides - $apiEndpointURI = "admin/workspaces/delegatedTenantSettingOverrides" - - # Step 3: Invoke the Fabric API to retrieve workspaces tenant setting overrides - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Get - - # Step 4: Check if any workspaces tenant setting overrides were retrieved and handle results accordingly - if ($response) { - Write-Message -Message "Successfully retrieved workspaces tenant setting overrides." -Level Debug - return $response - } else { - Write-Message -Message "No workspaces tenant setting overrides found." -Level Warning - return $null - } - } catch { - # Step 5: Log detailed error information if the API request fails - $errorDetails = $_.Exception.Message - Write-Message -Message "Error retrieving workspaces tenant setting overrides: $errorDetails" -Level Error - } -} diff --git a/source/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 b/source/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 deleted file mode 100644 index fc7a3240..00000000 --- a/source/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 +++ /dev/null @@ -1,93 +0,0 @@ -function Add-FabricWorkspaceIdentity { - <# - .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 - Provisions a Managed Identity for the workspace with ID "workspace123". - - ```powershell - Add-FabricWorkspaceIdentity -WorkspaceId "workspace123" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [Alias("Id")] - [guid]$WorkspaceId - ) - - try { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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/source/Public/Workspace/Get-FabricWorkspace.ps1 b/source/Public/Workspace/Get-FabricWorkspace.ps1 deleted file mode 100644 index f290d907..00000000 --- a/source/Public/Workspace/Get-FabricWorkspace.ps1 +++ /dev/null @@ -1,139 +0,0 @@ -function Get-FabricWorkspace { - <# - .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 - Fetches details of the workspace with ID "workspace123". - - ```powershell - Get-FabricWorkspace -WorkspaceId "workspace123" - ``` - - .EXAMPLE - Fetches details of the workspace with the name "MyWorkspace". - - ```powershell - Get-FabricWorkspace -WorkspaceName "MyWorkspace" - ``` - - .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` 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 - #> - [CmdletBinding()] - param ( - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [Alias("Id")] - [guid]$WorkspaceId, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [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 - Confirm-TokenState - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 - } -} diff --git a/source/Public/Workspace/New-FabricWorkspace.ps1 b/source/Public/Workspace/New-FabricWorkspace.ps1 deleted file mode 100644 index 247df3f6..00000000 --- a/source/Public/Workspace/New-FabricWorkspace.ps1 +++ /dev/null @@ -1,135 +0,0 @@ -function New-FabricWorkspace -{ - <# -.SYNOPSIS -Creates a new Fabric workspace with the specified display name. - -.DESCRIPTION -The `New-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. - -.PARAMETER WorkspaceDescription -(Optional) A description for the workspace. This parameter is optional. - -.PARAMETER CapacityId -(Optional) The ID of the capacity to be associated with the workspace. This parameter is optional. - -.EXAMPLE - Creates a workspace named "NewWorkspace". - - ```powershell - New-FabricWorkspace -WorkspaceName "NewWorkspace" - ``` - -.NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Calls `Confirm-TokenState` to ensure token validity before making the API request. - -Author: Tiago Balabuch - #> - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string]$WorkspaceName, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [string]$WorkspaceDescription, - - [Parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [guid]$CapacityId - ) - - try - { - # Step 1: Ensure token validity - Confirm-TokenState - - # 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 - - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create Workspace")) - { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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/specs/001-add-useragent/checklists/requirements.md b/specs/001-add-useragent/checklists/requirements.md deleted file mode 100644 index 1585b90f..00000000 --- a/specs/001-add-useragent/checklists/requirements.md +++ /dev/null @@ -1,40 +0,0 @@ -# Specification Quality Checklist: Add UserAgent attribute to all request to Fabric API - -**Purpose**: Validate specification completeness and quality before proceeding to planning -**Created**: 2026-01-11 -**Feature**: [spec.md](specs/001-add-useragent/spec.md) - -## Content Quality - -- [x] No implementation details (languages, frameworks, APIs) - - Result: PASS — Implementation details moved to `implementation-notes.md` and removed from high-level spec. -- [x] Focused on user value and business needs -- [x] Written for non-technical stakeholders (mostly) - - Note: Spec includes some technical wording; consider moving implementation guidance to a separate `implementation-notes.md`. -- [x] All mandatory sections completed - -## Requirement Completeness - - - [x] No [NEEDS CLARIFICATION] markers remain - - Result: PASS — Clarification resolved: UA override policy set to Default-only (no override). -- [x] Requirements are testable and unambiguous - - [x] Success criteria are measurable - - Result: PASS — Measurable; updated spec to remove tooling references. - - [x] Success criteria are technology-agnostic (no implementation details) - - Result: PASS — Tooling references removed from the high-level spec (moved to implementation-notes.md). -- [x] All acceptance scenarios are defined -- [x] Edge cases are identified -- [x] Scope is clearly bounded -- [x] Dependencies and assumptions identified - -## Feature Readiness - -- [x] All functional requirements have clear acceptance criteria -- [x] User scenarios cover primary flows -- [x] Feature meets measurable outcomes defined in Success Criteria - - [x] No implementation details leak into specification - - Result: PASS — Implementation details were moved to `implementation-notes.md`. - -## Notes - -- Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan` diff --git a/specs/001-add-useragent/implementation-notes.md b/specs/001-add-useragent/implementation-notes.md deleted file mode 100644 index 9fb5e938..00000000 --- a/specs/001-add-useragent/implementation-notes.md +++ /dev/null @@ -1,42 +0,0 @@ -# Implementation Notes: Add UserAgent attribute to Fabric API requests - -This file contains developer-focused guidance and implementation details moved out of the high-level specification. - -1) Where to inject the header - -- Locate the central HTTP layer used by the module (the single place where HTTP requests are created and sent). Examples in the codebase include request helper functions and wrappers; update that location so the `User-Agent` header is injected before sending. - -2) User-Agent composition - -- Canonical format (enforced by spec): - - powershell/,FabricTools/,(; ) - -- Recommended runtime lookups: - - - PowerShell runtime: `$PSVersionTable.PSVersion` (fallback: `unknown`) - - Module version: read from the loaded module manifest `ModuleVersion` or embed via build-time substitution (fallback: `unknown`) - - OS: use platform API (e.g., `[System.Runtime.InteropServices.RuntimeInformation]::OSDescription`) and normalize to a short token (e.g., `linux`, `windows`, `darwin`) - - Arch: detect 64-bit vs 32-bit (e.g., `([System.Environment]::Is64BitOperatingSystem ? 'amd64' : 'x86')`), or map runtime architecture values to a short token - -3) Header constraints and validation - -- Ensure header value length is reasonable; trim or normalize fields if necessary to avoid server rejections. -- Do not overwrite or remove existing headers such as `Authorization` or `Content-Type`. - -4) Testing guidance - -- Unit tests: mock the HTTP layer and assert the header exists and follows the canonical pattern. Avoid referencing specific test frameworks in the high-level spec; implement tests using the project's testing conventions (Pester in this repo). -- Integration tests: use a recording/mocking approach to verify header transmitted in end-to-end flows where feasible. - -5) Configuration policy - -- Per spec decision, the `User-Agent` will NOT be user-overridable. Do not add an environment variable or module config parameter for overriding UA in this change. - -6) Backwards compatibility - -- Implement the header in a non-breaking way. Existing public function signatures and behaviors MUST NOT change. - -7) Developer notes - -- Keep code changes centralized and minimal. Add comments referencing the spec and include changelog entry. diff --git a/specs/001-add-useragent/spec.md b/specs/001-add-useragent/spec.md deleted file mode 100644 index c3ff7245..00000000 --- a/specs/001-add-useragent/spec.md +++ /dev/null @@ -1,225 +0,0 @@ -```markdown -# Feature Specification: Add UserAgent attribute to all request to Fabric API - -**Feature Branch**: `001-add-useragent` -**Created**: 2026-01-11 -**Status**: Draft -**Input**: Issue: "Add UserAgent attribute to all request to Fabric API" (https://github.com/dataplat/FabricTools/issues/119) - -## User Scenarios & Testing *(mandatory)* - -### User Story 1 - Ensure all Fabric API requests include a User-Agent header (Priority: P1) - -As a module user or maintainer, I want every HTTP request sent to Microsoft Fabric to include a `User-Agent` header so that telemetry and debug logs on the Fabric side include the client and runtime details. - -**Why this priority**: Improves observability, troubleshooting, and helps Fabric identify client versions and runtimes; low risk, high visibility. - -**Independent Test**: Unit tests that exercise the internal HTTP wrapper(s) assert the presence and format of the `User-Agent` header. Integration tests (mock or recording) verify the header is included in real requests. - -**Acceptance Scenarios**: - -1. **Given** a code path that issues a Fabric API call, **When** the call is executed, **Then** the outgoing request contains a `User-Agent` header following the project's format. -2. **Given** a developer overrides or configures the user-agent (if allowed), **When** a call is made, **Then** the header reflects the override and remains valid. - ---- - -### User Story 2 - Backwards compatibility and configurability (Priority: P2) - -As an administrator, I want the `User-Agent` to be configurable or overridable so that automation or enterprise environments can adapt the header when required. - -**Why this priority**: Allowing controlled overrides reduces friction for environments that require customized client identifiers. - -**Independent Test**: A configuration path (module config, env var, or parameter) can override the UA; unit tests verify override behavior. - -**Acceptance Scenarios**: - -1. **Given** the module configuration sets a custom `User-Agent`, **When** the call is made, **Then** the outgoing header equals the configured value. - ---- - -### Edge Cases - -- What happens when runtime information (PowerShell version, OS, arch) cannot be determined? The implementation MUST fall back to sensible placeholders (e.g., `unknown`). -- Header length should be reasonable; the implementation MUST avoid excessively long values that could be rejected by servers. -- The change must not remove or break existing authentication or header logic (Authorization, Content-Type, etc.). - -## Requirements *(mandatory)* - -### Functional Requirements - -- **FR-001**: All outgoing HTTP requests to Microsoft Fabric APIs MUST include an HTTP `User-Agent` header. -- **FR-002**: The `User-Agent` header MUST follow the canonical format: `powershell/,FabricTools/,(; )` (example: `powershell/7.5,FabricTools/0.26.0,(linux; amd64)`). -- **FR-003**: The header value MUST include PowerShell runtime version and FabricTools module version. If any value is unavailable it MUST use `unknown` in that section. -- **FR-004**: The `User-Agent` implementation MUST be applied centrally (single internal HTTP wrapper or helper) so that all public commands automatically inherit the header without per-cmdlet changes. -- **FR-005**: There MUST be unit tests asserting the `User-Agent` header is present and matches the expected pattern for the internal HTTP layer. -- **FR-006**: The `User-Agent` header MUST NOT be user-overridable; the module manages the header centrally and enforces the canonical format. -- **FR-007**: No existing public behavior (parameters, returned values, authorization) MUST be altered by this change. - -*Notes / Assumptions:* The module build produces a version (manifest `ModuleVersion`) that can be read at runtime; the implementation may read it from the loaded module manifest or from a build constant. - -## Key Entities - -- **HTTP Wrapper / Fabric Client**: The internal helper responsible for issuing HTTP requests (e.g., `Invoke-FabricRestMethod` helper). This is the preferred place to inject the header. -- **User-Agent string**: Structured value composed of runtime, module version, and environment. -- **Config source**: Module-level config or environment variables that allow override of default UA value. - -## Success Criteria *(mandatory)* - -### Measurable Outcomes - -- **SC-001**: 100% of unit-tested outgoing HTTP requests include a `User-Agent` header. -- **SC-002**: Unit tests cover the UA header presence and pattern with at least one unit test per HTTP wrapper. -- **SC-003**: Integration test(s) (recorded or mocked) verify that an HTTP request to a test endpoint contains the header. -- **SC-004**: No regression in existing tests; all CI checks remain green after the change. - -## Implementation Notes - -Implementation details have been moved to `implementation-notes.md` in this feature folder. That file contains developer guidance, suggested runtime lookups, testing guidance, and header constraints. The high-level specification intentionally avoids tool- and function-level details. - -## UA override policy (decision) - -Decision: **Option A — Default-only (no override)** - -Rationale: the project will manage `User-Agent` centrally to guarantee consistent telemetry and reduce configuration surface. The header will not be exposed for override via environment variables, module config, or per-call parameters. If enterprise requirements arise later, the policy may be revisited in a new change request. - ---- - -## Tasks (high level) - -- T001: Identify the central HTTP helper(s) that issue Fabric API requests. -- T002: Add logic to construct the `User-Agent` string from runtime and module metadata. -- T003: Inject the header in the central HTTP helper and ensure it's sent with every request. -- T004: Add unit tests for header presence and format. -- T005: Add an integration test (mock or recording) verifying header arrival. -- T006: Update documentation (`docs/en-US` entry or a short README section) describing the UA format and override policy. - ---- - -## Success Checklist (for implementation) - -- [ ] Central HTTP helper updated to include `User-Agent`. -- [ ] Unit tests added and passing. -- [ ] Integration test added and passing (recorded or mocked). -- [ ] Documentation updated with UA format and override instructions. -- [ ] PR includes `CHANGELOG.md` entry under `Unreleased`. - ---- - -**Prepared by**: automation (`/speckit.specify`) on 2026-01-11 - -``` -# Feature Specification: [FEATURE NAME] - -**Feature Branch**: `[###-feature-name]` -**Created**: [DATE] -**Status**: Draft -**Input**: User description: "$ARGUMENTS" - -## User Scenarios & Testing *(mandatory)* - - - -### User Story 1 - [Brief Title] (Priority: P1) - -[Describe this user journey in plain language] - -**Why this priority**: [Explain the value and why it has this priority level] - -**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"] - -**Acceptance Scenarios**: - -1. **Given** [initial state], **When** [action], **Then** [expected outcome] -2. **Given** [initial state], **When** [action], **Then** [expected outcome] - ---- - -### User Story 2 - [Brief Title] (Priority: P2) - -[Describe this user journey in plain language] - -**Why this priority**: [Explain the value and why it has this priority level] - -**Independent Test**: [Describe how this can be tested independently] - -**Acceptance Scenarios**: - -1. **Given** [initial state], **When** [action], **Then** [expected outcome] - ---- - -### User Story 3 - [Brief Title] (Priority: P3) - -[Describe this user journey in plain language] - -**Why this priority**: [Explain the value and why it has this priority level] - -**Independent Test**: [Describe how this can be tested independently] - -**Acceptance Scenarios**: - -1. **Given** [initial state], **When** [action], **Then** [expected outcome] - ---- - -[Add more user stories as needed, each with an assigned priority] - -### Edge Cases - - - -- What happens when [boundary condition]? -- How does system handle [error scenario]? - -## Requirements *(mandatory)* - - - -### Functional Requirements - -- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"] -- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"] -- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"] -- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"] -- **FR-005**: System MUST [behavior, e.g., "log all security events"] - -*Example of marking unclear requirements:* - -- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?] -- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified] - -### Key Entities *(include if feature involves data)* - -- **[Entity 1]**: [What it represents, key attributes without implementation] -- **[Entity 2]**: [What it represents, relationships to other entities] - -## Success Criteria *(mandatory)* - - - -### Measurable Outcomes - -- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"] -- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"] -- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"] -- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"] diff --git a/source/FabricTools.psd1 b/src/FabricTools.psd1 similarity index 98% rename from source/FabricTools.psd1 rename to src/FabricTools.psd1 index f2bb280c..c345f0d1 100644 --- a/source/FabricTools.psd1 +++ b/src/FabricTools.psd1 @@ -58,7 +58,7 @@ RequiredModules = @( @{ ModuleName = 'Az.Accounts' ; ModuleVersion = '5.0.0' }, @{ ModuleName = 'MicrosoftPowerBIMgmt.Profile' ; ModuleVersion = '1.2.1111' }, @{ ModuleName = 'Az.Resources' ; ModuleVersion = '6.15.1' }, - @{ ModuleName = 'PSFramework' ; ModuleVersion = '1.0.0' } + @{ ModuleName = 'PSFramework' ; ModuleVersion = '1.13.426' } ) # Assemblies that must be loaded prior to importing this module. diff --git a/source/FabricTools.psm1 b/src/FabricTools.psm1 similarity index 100% rename from source/FabricTools.psm1 rename to src/FabricTools.psm1 diff --git a/source/Private/Confirm-TokenState.ps1 b/src/Private/Confirm-TokenState.ps1 similarity index 100% rename from source/Private/Confirm-TokenState.ps1 rename to src/Private/Confirm-TokenState.ps1 diff --git a/source/Private/Get-FabricContinuationToken.ps1 b/src/Private/Get-FabricContinuationToken.ps1 similarity index 100% rename from source/Private/Get-FabricContinuationToken.ps1 rename to src/Private/Get-FabricContinuationToken.ps1 diff --git a/source/Private/Get-FabricUserAgent.ps1 b/src/Private/Get-FabricUserAgent.ps1 similarity index 100% rename from source/Private/Get-FabricUserAgent.ps1 rename to src/Private/Get-FabricUserAgent.ps1 diff --git a/source/Private/Get-FileDefinitionParts.ps1 b/src/Private/Get-FileDefinitionParts.ps1 similarity index 91% rename from source/Private/Get-FileDefinitionParts.ps1 rename to src/Private/Get-FileDefinitionParts.ps1 index 1131e74c..6b5f79f3 100644 --- a/source/Private/Get-FileDefinitionParts.ps1 +++ b/src/Private/Get-FileDefinitionParts.ps1 @@ -7,7 +7,7 @@ function Get-FileDefinitionParts { ) try { if (-Not (Test-Path $sourceDirectory)) { - Write-Message -Message "The specified source directory does not exist: $sourceDirectory" -Level Error + Write-Message -Message "The specified source directory does not exist: $sourceDirectory" -Level Error throw } @@ -21,28 +21,28 @@ function Get-FileDefinitionParts { # 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 += @{ + + $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 + # 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: $_" diff --git a/source/Private/Set-FabConfig.ps1 b/src/Private/Set-FabConfig.ps1 similarity index 100% rename from source/Private/Set-FabConfig.ps1 rename to src/Private/Set-FabConfig.ps1 diff --git a/source/Private/Test-FabricApiResponse.ps1 b/src/Private/Test-FabricApiResponse.ps1 similarity index 98% rename from source/Private/Test-FabricApiResponse.ps1 rename to src/Private/Test-FabricApiResponse.ps1 index e9773304..b719c099 100644 --- a/source/Private/Test-FabricApiResponse.ps1 +++ b/src/Private/Test-FabricApiResponse.ps1 @@ -89,9 +89,7 @@ function Test-FabricApiResponse { switch ($statusCode) { 200 { - if ($Operation -eq 'Get') { - $result = $Response - } + $result = $Response } 201 { $result = $Response diff --git a/source/Private/Write-Message.ps1 b/src/Private/Write-Message.ps1 similarity index 100% rename from source/Private/Write-Message.ps1 rename to src/Private/Write-Message.ps1 diff --git a/source/Public/Capacity/Get-FabricCapacities.ps1 b/src/Public/Capacity/Get-FabricCapacities.ps1 similarity index 100% rename from source/Public/Capacity/Get-FabricCapacities.ps1 rename to src/Public/Capacity/Get-FabricCapacities.ps1 diff --git a/source/Public/Capacity/Get-FabricCapacity.ps1 b/src/Public/Capacity/Get-FabricCapacity.ps1 similarity index 97% rename from source/Public/Capacity/Get-FabricCapacity.ps1 rename to src/Public/Capacity/Get-FabricCapacity.ps1 index 3532e309..6c1af2c3 100644 --- a/source/Public/Capacity/Get-FabricCapacity.ps1 +++ b/src/Public/Capacity/Get-FabricCapacity.ps1 @@ -54,11 +54,11 @@ function Get-FabricCapacity { Confirm-TokenState # Construct the API endpoint URL - $apiEndpointURI = "capacities" + $apiEndpointUrl = "capacities" # Invoke the Fabric API to retrieve capacity details $apiParams = @{ - Uri = $apiEndpointURI + Uri = $apiEndpointUrl Method = 'Get' } $capacities = (Invoke-FabricRestMethod @apiParams).Value diff --git a/src/Public/Capacity/Get-FabricCapacityRefreshables.ps1 b/src/Public/Capacity/Get-FabricCapacityRefreshables.ps1 new file mode 100644 index 00000000..306a3903 --- /dev/null +++ b/src/Public/Capacity/Get-FabricCapacityRefreshables.ps1 @@ -0,0 +1,57 @@ +function Get-FabricCapacityRefreshables { + <# +.SYNOPSIS +Returns a list of refreshables for all capacities that the user has access to. + +.DESCRIPTION +The Get-FabricCapacityRefreshables function returns refreshables (datasets with refresh activity) +for all capacities the user has access to. Power BI retains a seven-day refresh history for each +dataset, up to a maximum of 60 refreshes. + +Requires scope: Capacity.Read.All or Capacity.ReadWrite.All + +.PARAMETER top +Required. Returns only the first n results. Must be a positive integer (minimum: 1). + +.PARAMETER expand +Optional. Accepts a comma-separated list of data types to expand inline in the response. +Supported values: 'capacity', 'group'. + +.PARAMETER filter +Optional. Returns a subset of results based on an OData filter query condition. + +.PARAMETER skip +Optional. Skips the first n results. Use together with -top to fetch results beyond the first 1000. + +.EXAMPLE + Retrieves the top 10 refreshables across all capacities. + + ```powershell + Get-FabricCapacityRefreshables -top 10 + ``` + +.EXAMPLE + Retrieves the top 5 refreshables with capacity details expanded. + + ```powershell + Get-FabricCapacityRefreshables -top 5 -expand 'capacity' + ``` + +.NOTES +Author: Ioana Bouariu + + #> + + # Define a mandatory parameter for the number of top refreshable capacities to retrieve. + Param ( + [Parameter(Mandatory = $false)] + [string]$top = 5 + ) + + Confirm-TokenState + + # Make a GET request to the PowerBI API to retrieve the top refreshable capacities. + # The function returns the 'value' property of the response. + $result = Invoke-FabricRestMethod -Method GET -PowerBIApi -Uri "capacities/refreshables?`$top=$top" + $result.value +} diff --git a/source/Public/Capacity/Get-FabricCapacitySkus.ps1 b/src/Public/Capacity/Get-FabricCapacitySkus.ps1 similarity index 100% rename from source/Public/Capacity/Get-FabricCapacitySkus.ps1 rename to src/Public/Capacity/Get-FabricCapacitySkus.ps1 diff --git a/source/Public/Capacity/Get-FabricCapacityState.ps1 b/src/Public/Capacity/Get-FabricCapacityState.ps1 similarity index 100% rename from source/Public/Capacity/Get-FabricCapacityState.ps1 rename to src/Public/Capacity/Get-FabricCapacityState.ps1 diff --git a/source/Public/Capacity/Get-FabricCapacityTenantOverrides.ps1 b/src/Public/Capacity/Get-FabricCapacityTenantOverrides.ps1 similarity index 100% rename from source/Public/Capacity/Get-FabricCapacityTenantOverrides.ps1 rename to src/Public/Capacity/Get-FabricCapacityTenantOverrides.ps1 diff --git a/source/Public/Capacity/Get-FabricCapacityWorkload.ps1 b/src/Public/Capacity/Get-FabricCapacityWorkload.ps1 similarity index 100% rename from source/Public/Capacity/Get-FabricCapacityWorkload.ps1 rename to src/Public/Capacity/Get-FabricCapacityWorkload.ps1 diff --git a/source/Public/Capacity/Resume-FabricCapacity.ps1 b/src/Public/Capacity/Resume-FabricCapacity.ps1 similarity index 100% rename from source/Public/Capacity/Resume-FabricCapacity.ps1 rename to src/Public/Capacity/Resume-FabricCapacity.ps1 diff --git a/source/Public/Capacity/Suspend-FabricCapacity.ps1 b/src/Public/Capacity/Suspend-FabricCapacity.ps1 similarity index 100% rename from source/Public/Capacity/Suspend-FabricCapacity.ps1 rename to src/Public/Capacity/Suspend-FabricCapacity.ps1 diff --git a/source/Public/Capacity/Update-FabricCapacity.ps1 b/src/Public/Capacity/Update-FabricCapacity.ps1 similarity index 95% rename from source/Public/Capacity/Update-FabricCapacity.ps1 rename to src/Public/Capacity/Update-FabricCapacity.ps1 index fea7c502..e6f21bbe 100644 --- a/source/Public/Capacity/Update-FabricCapacity.ps1 +++ b/src/Public/Capacity/Update-FabricCapacity.ps1 @@ -104,13 +104,13 @@ function Update-FabricCapacity try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "$($AzureSession.BaseApiUrl)/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Fabric/capacities/{2}?api-version=2023-11-01" -f $SubscriptionId, $ResourceGroupName, $CapacityName - # Step 3: Construct the request body + # Construct the request body $body = @{ properties = @{ administration = @{ @@ -129,7 +129,7 @@ function Update-FabricCapacity $body.tags = $Tags } - # Step 4: Make the API request + # Make the API request if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Fabric Capacity")) { $apiParams = @{ @@ -147,7 +147,7 @@ function Update-FabricCapacity } catch { - # Step 5: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Fabric Capacity. Error: $errorDetails" -Level Error throw diff --git a/source/Public/Config/Get-FabricConfig.ps1 b/src/Public/Config/Get-FabricConfig.ps1 similarity index 100% rename from source/Public/Config/Get-FabricConfig.ps1 rename to src/Public/Config/Get-FabricConfig.ps1 diff --git a/source/Public/Connect-FabricAccount.ps1 b/src/Public/Connect-FabricAccount.ps1 similarity index 86% rename from source/Public/Connect-FabricAccount.ps1 rename to src/Public/Connect-FabricAccount.ps1 index 077294bb..21ee28b1 100644 --- a/source/Public/Connect-FabricAccount.ps1 +++ b/src/Public/Connect-FabricAccount.ps1 @@ -152,7 +152,14 @@ function Connect-FabricAccount { if ($PSCmdlet.ShouldProcess("Setting Fabric authentication token and headers for $($azContext.Account)")) { $ResourceUrl = Get-PSFConfigValue -FullName 'FabricTools.FabricApi.ResourceUrl' Write-Message "Get authentication token from $ResourceUrl" -Level Verbose - $accessToken = (Get-AzAccessToken -ResourceUrl $ResourceUrl) + try { + $accessToken = Get-AzAccessToken -ResourceUrl $ResourceUrl -ErrorAction Stop + } catch { + Write-Message "Token acquisition failed for $ResourceUrl (MFA or conditional access may have expired). Re-authenticating with resource scope..." -Level Warning + $reconnectTenantId = if ($TenantId) { $TenantId } else { $azContext.Tenant.Id } + $null = Connect-AzAccount -Tenant $reconnectTenantId -AuthScope $ResourceUrl + $accessToken = Get-AzAccessToken -ResourceUrl $ResourceUrl -ErrorAction Stop + } Set-PSFConfig -FullName 'FabricTools.FabricSession.AccessToken' -Value $accessToken $plainTextToken = $accessToken.Token | ConvertFrom-SecureString -AsPlainText Write-Message "Setup headers for Fabric API calls" -Level Debug @@ -165,7 +172,14 @@ function Connect-FabricAccount { if ($PSCmdlet.ShouldProcess("Setting Azure authentication token and headers for $($azContext.Account)")) { $BaseApiUrl = Get-PSFConfigValue -FullName 'FabricTools.AzureApi.BaseUrl' Write-Message "Get authentication token from $BaseApiUrl" -Level Verbose - $accessToken = (Get-AzAccessToken -ResourceUrl $BaseApiUrl) + try { + $accessToken = Get-AzAccessToken -ResourceUrl $BaseApiUrl -ErrorAction Stop + } catch { + Write-Message "Token acquisition failed for $BaseApiUrl (MFA or conditional access may have expired). Re-authenticating with resource scope..." -Level Warning + $reconnectTenantId = if ($TenantId) { $TenantId } else { $azContext.Tenant.Id } + $null = Connect-AzAccount -Tenant $reconnectTenantId -AuthScope $BaseApiUrl + $accessToken = Get-AzAccessToken -ResourceUrl $BaseApiUrl -ErrorAction Stop + } Set-PSFConfig -FullName 'FabricTools.AzureSession.AccessToken' -Value $accessToken $plainTextToken = $accessToken.Token | ConvertFrom-SecureString -AsPlainText Write-Message "Setup headers for Azure API calls" -Level Debug diff --git a/source/Public/Copy Job/Get-FabricCopyJob.ps1 b/src/Public/Copy Job/Get-FabricCopyJob.ps1 similarity index 94% rename from source/Public/Copy Job/Get-FabricCopyJob.ps1 rename to src/Public/Copy Job/Get-FabricCopyJob.ps1 index 0710308b..f77f1a93 100644 --- a/source/Public/Copy Job/Get-FabricCopyJob.ps1 +++ b/src/Public/Copy Job/Get-FabricCopyJob.ps1 @@ -63,11 +63,11 @@ function Get-FabricCopyJob { # Construct the API endpoint URL - $apiEndpointURI = "workspaces/{0}/copyJobs" -f $WorkspaceId + $apiEndpointUrl = "workspaces/{0}/copyJobs" -f $WorkspaceId # Invoke the Fabric API to retrieve capacity details $apiParams = @{ - Uri = $apiEndpointURI + Uri = $apiEndpointUrl Method = 'Get' } $copyJobs = Invoke-FabricRestMethod @apiParams @@ -83,7 +83,7 @@ function Get-FabricCopyJob { $copyJobs } - # Step 9: Handle results + # Handle results if ($response) { Write-Message -Message "CopyJob found matching the specified criteria." -Level Debug return $response @@ -92,7 +92,7 @@ function Get-FabricCopyJob { return $null } } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve CopyJob. Error: $errorDetails" -Level Error } diff --git a/source/Public/Copy Job/Get-FabricCopyJobDefinition.ps1 b/src/Public/Copy Job/Get-FabricCopyJobDefinition.ps1 similarity index 82% rename from source/Public/Copy Job/Get-FabricCopyJobDefinition.ps1 rename to src/Public/Copy Job/Get-FabricCopyJobDefinition.ps1 index ac3a0daf..0d7d59f5 100644 --- a/source/Public/Copy Job/Get-FabricCopyJobDefinition.ps1 +++ b/src/Public/Copy Job/Get-FabricCopyJobDefinition.ps1 @@ -48,29 +48,29 @@ Author: Tiago Balabuch ) try { - # Step 1: Validate authentication token before proceeding. + # Validate authentication token before proceeding. Confirm-TokenState - # Step 2: Construct the API endpoint URL for retrieving the Copy Job definition. + # Construct the API endpoint URL for retrieving the Copy Job definition. $apiEndpointUrl = "workspaces/{0}/copyJobs/{1}/getDefinition" -f $WorkspaceId, $CopyJobId - # Step 3: Append the format query parameter if specified by the user. + # Append the format query parameter if specified by the user. if ($CopyJobFormat) { $apiEndpointUrl = "{0}?format={1}" -f $apiEndpointUrl, $CopyJobFormat } Write-Message -Message "Constructed API Endpoint URL: $apiEndpointUrl" -Level Debug - # Step 4: Execute the API request to retrieve the Copy Job definition. + # Execute the API request to retrieve the Copy Job definition. $apiParams = @{ Uri = $apiEndpointUrl Method = 'POST' } $response = Invoke-FabricRestMethod @apiParams - # Step 5: Return the API response containing the Copy Job definition. + # Return the API response containing the Copy Job definition. return $response } catch { - # Step 6: Capture and log detailed error information for troubleshooting. + # Capture and log detailed error information for troubleshooting. $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve Copy Job definition. Error: $errorDetails" -Level Error } diff --git a/source/Public/Copy Job/New-FabricCopyJob.ps1 b/src/Public/Copy Job/New-FabricCopyJob.ps1 similarity index 84% rename from source/Public/Copy Job/New-FabricCopyJob.ps1 rename to src/Public/Copy Job/New-FabricCopyJob.ps1 index 48a80ae9..a3857fcb 100644 --- a/source/Public/Copy Job/New-FabricCopyJob.ps1 +++ b/src/Public/Copy Job/New-FabricCopyJob.ps1 @@ -30,10 +30,9 @@ function New-FabricCopyJob { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -59,14 +58,14 @@ function New-FabricCopyJob { ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointURI = "workspaces/{0}/copyJobs" -f $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointURI" -Level Debug + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/copyJobs" -f $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $CopyJobName } @@ -75,7 +74,7 @@ function New-FabricCopyJob { $body.description = $CopyJobDescription } - # Step 4: Add copy job definition file content if provided + # Add copy job definition file content if provided if ($CopyJobPathDefinition) { $CopyJobEncodedContent = Convert-ToBase64 -filePath $CopyJobPathDefinition @@ -98,7 +97,7 @@ function New-FabricCopyJob { return $null } } - #Step 5: Add platform definition file content if provided + # Add platform definition file content if provided if ($CopyJobPathPlatformDefinition) { $CopyJobEncodedPlatformContent = Convert-ToBase64 -filePath $CopyJobPathPlatformDefinition @@ -125,13 +124,16 @@ function New-FabricCopyJob { $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if($PSCmdlet.ShouldProcess($apiEndpointURI, "Create Copy Job")) { + if($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create Copy Job")) { - # Step 6: Make the API request + # Make the API request $apiParams = @{ - Uri = $apiEndpointURI - Method = 'Post' - Body = $bodyJson + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'CopyJob' + ObjectIdOrName = $CopyJobName + HandleResponse = $true } $response = Invoke-FabricRestMethod @apiParams } @@ -140,7 +142,7 @@ function New-FabricCopyJob { return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create Copy Job. Error: $errorDetails" -Level Error } diff --git a/source/Public/Copy Job/Remove-FabricCopyJob.ps1 b/src/Public/Copy Job/Remove-FabricCopyJob.ps1 similarity index 65% rename from source/Public/Copy Job/Remove-FabricCopyJob.ps1 rename to src/Public/Copy Job/Remove-FabricCopyJob.ps1 index 82d9e922..dc9c3e20 100644 --- a/source/Public/Copy Job/Remove-FabricCopyJob.ps1 +++ b/src/Public/Copy Job/Remove-FabricCopyJob.ps1 @@ -21,10 +21,9 @@ function Remove-FabricCopyJob { ``` .NOTES - - Requires the `$FabricConfig` global configuration, which must include `BaseUrl` and `FabricHeaders`. - Ensures token validity by invoking `Confirm-TokenState` before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -36,28 +35,31 @@ function Remove-FabricCopyJob { [ValidateNotNullOrEmpty()] [guid]$CopyJobId ) + try { # Ensure token validity Confirm-TokenState # Construct the API endpoint URI - $apiEndpointURI = "workspaces/{0}/copyJobs/{1}" -f $WorkspaceId, $CopyJobId - Write-Message -Message "API Endpoint: $apiEndpointURI" -Level Debug - - if($PSCmdlet.ShouldProcess($apiEndpointURI, "Delete Copy Job")) { + $apiEndpointUrl = "workspaces/{0}/copyJobs/{1}" -f $WorkspaceId, $CopyJobId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + if ($PSCmdlet.ShouldProcess($CopyJobId, "Delete Copy Job")) + { + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'CopyJob' + ObjectIdOrName = $CopyJobId + HandleResponse = $true + } - # Make the API request - $apiParams = @{ - Uri = $apiEndpointURI - Method = 'DELETE' + $response = Invoke-FabricRestMethod @apiParams } - $response = Invoke-FabricRestMethod @apiParams - } - Write-Message -Message "Copy Job '$CopyJobId' deleted successfully from workspace '$WorkspaceId'." -Level Info - return $response + Write-Message -Message "Copy Job '$CopyJobId' deleted successfully from workspace '$WorkspaceId'." -Level Info + return $response -} catch { - # Log and handle errors + } catch { + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete Copy Job '$CopyJobId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Copy Job/Update-FabricCopyJob.ps1 b/src/Public/Copy Job/Update-FabricCopyJob.ps1 similarity index 78% rename from source/Public/Copy Job/Update-FabricCopyJob.ps1 rename to src/Public/Copy Job/Update-FabricCopyJob.ps1 index 7b31ebf0..5c02dcc8 100644 --- a/source/Public/Copy Job/Update-FabricCopyJob.ps1 +++ b/src/Public/Copy Job/Update-FabricCopyJob.ps1 @@ -28,10 +28,9 @@ function Update-FabricCopyJob ``` .NOTES - - Requires the `$FabricConfig` global configuration, which includes `BaseUrl` and `FabricHeaders`. - Ensures token validity by calling `Confirm-TokenState` before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -58,8 +57,8 @@ function Update-FabricCopyJob Confirm-TokenState # Construct the API endpoint URI - $apiEndpointURI = "workspaces/{0}/copyJobs/{1}" -f $WorkspaceId, $CopyJobId - Write-Message -Message "API Endpoint: $apiEndpointURI" -Level Debug + $apiEndpointUrl = "workspaces/{0}/copyJobs/{1}" -f $WorkspaceId, $CopyJobId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug # Construct the request body $body = @{ @@ -75,17 +74,22 @@ function Update-FabricCopyJob $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Update Copy Job")) + if ($PSCmdlet.ShouldProcess($CopyJobName, "Update Copy Job")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -method Patch ` - -body $bodyJson + $apiParams = @{ + Uri = "workspaces/$WorkspaceId/copyJobs/$CopyJobId" + Method = 'Patch' + Body = $bodyJson + TypeName = 'CopyJob' + ObjectIdOrName = $CopyJobName + HandleResponse = $true + } + + $response = Invoke-FabricRestMethod @apiParams } Write-Message -Message "Copy Job '$CopyJobName' updated successfully!" -Level Info - return $response + $response } catch { diff --git a/source/Public/Copy Job/Update-FabricCopyJobDefinition.ps1 b/src/Public/Copy Job/Update-FabricCopyJobDefinition.ps1 similarity index 81% rename from source/Public/Copy Job/Update-FabricCopyJobDefinition.ps1 rename to src/Public/Copy Job/Update-FabricCopyJobDefinition.ps1 index c88212a1..76406e4a 100644 --- a/source/Public/Copy Job/Update-FabricCopyJobDefinition.ps1 +++ b/src/Public/Copy Job/Update-FabricCopyJobDefinition.ps1 @@ -34,12 +34,10 @@ The Copy Job content and platform-specific definitions can be provided as file p ``` .NOTES -- Requires the `$FabricConfig` global configuration, which must include `BaseUrl` and `FabricHeaders`. - Validates token expiration using `Confirm-TokenState` before making the API request. - Encodes file content as Base64 before sending it to the Fabric API. -- Logs detailed messages for debugging and error handling. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -60,19 +58,17 @@ Author: Tiago Balabuch [string]$CopyJobPathPlatformDefinition ) - try { - # Step 1: Ensure token validity + try { + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/copyJobs/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $CopyJobId - + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/copyJobs/$CopyJobId/updateDefinition" if ($CopyJobPathPlatformDefinition) { - $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + $apiEndpointUrl += "?updateMetadata=true" } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body $body = @{ definition = @{ parts = @() @@ -113,20 +109,24 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Copy Job Definition")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -BaseURI $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Copy Job Definition")) + { + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'CopyJob' + ObjectIdOrName = $CopyJobId + HandleResponse = $true + } - Write-Message -Message "Copy Job updated successfully!" -Level Info + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Copy Job '$CopyJobId' definition updated successfully!" -Level Info + } return $response - } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Copy Job. Error: $errorDetails" -Level Error } diff --git a/source/Public/Dashboard/Get-FabricDashboard.ps1 b/src/Public/Dashboard/Get-FabricDashboard.ps1 similarity index 93% rename from source/Public/Dashboard/Get-FabricDashboard.ps1 rename to src/Public/Dashboard/Get-FabricDashboard.ps1 index 5cd972ea..03f5987d 100644 --- a/source/Public/Dashboard/Get-FabricDashboard.ps1 +++ b/src/Public/Dashboard/Get-FabricDashboard.ps1 @@ -35,11 +35,11 @@ function Get-FabricDashboard { Confirm-TokenState # Construct the API endpoint URL - $apiEndpointURI = "workspaces/{0}/dashboards" -f $WorkspaceId + $apiEndpointUrl = "workspaces/{0}/dashboards" -f $WorkspaceId # Invoke the Fabric API to retrieve capacity details $apiParams = @{ - Uri = $apiEndpointURI + Uri = $apiEndpointUrl Method = 'Get' } $Dashboards = Invoke-FabricRestMethod @apiParams diff --git a/source/Public/Data Pipeline/Get-FabricDataPipeline.ps1 b/src/Public/Data Pipeline/Get-FabricDataPipeline.ps1 similarity index 92% rename from source/Public/Data Pipeline/Get-FabricDataPipeline.ps1 rename to src/Public/Data Pipeline/Get-FabricDataPipeline.ps1 index 27277c17..3904a13e 100644 --- a/source/Public/Data Pipeline/Get-FabricDataPipeline.ps1 +++ b/src/Public/Data Pipeline/Get-FabricDataPipeline.ps1 @@ -52,7 +52,7 @@ function Get-FabricDataPipeline { ) try { - # Step 1: Handle ambiguous input + # Handle ambiguous input if ($DataPipelineId -and $DataPipelineName) { Write-Message -Message "Both 'DataPipelineId' and 'DataPipelineName' were provided. Please specify only one." -Level Error return $null @@ -62,10 +62,14 @@ function Get-FabricDataPipeline { Confirm-TokenState # Construct the API endpoint URL - $apiEndpointURI = ("workspaces/{0}/dataPipelines" -f $WorkspaceId) + $apiEndpointUrl = ("workspaces/{0}/dataPipelines" -f $WorkspaceId) # Invoke the Fabric API to retrieve data pipeline details - $DataPipelines = (Invoke-FabricRestMethod -uri $apiEndpointURI -Method Get).Value + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + } + $DataPipelines = (Invoke-FabricRestMethod @apiParams).Value # Filter results based on provided parameters $response = if ($DataPipelineId) { diff --git a/source/Public/Data Pipeline/New-FabricDataPipeline.ps1 b/src/Public/Data Pipeline/New-FabricDataPipeline.ps1 similarity index 82% rename from source/Public/Data Pipeline/New-FabricDataPipeline.ps1 rename to src/Public/Data Pipeline/New-FabricDataPipeline.ps1 index 96f07620..6b3bbfb4 100644 --- a/source/Public/Data Pipeline/New-FabricDataPipeline.ps1 +++ b/src/Public/Data Pipeline/New-FabricDataPipeline.ps1 @@ -48,14 +48,14 @@ function New-FabricDataPipeline try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointURI = ("workspaces/{0}/dataPipelines" -f $WorkspaceId) - Write-Message -Message "API Endpoint: $apiEndpointURI" -Level Debug + # Construct the API URL + $apiEndpointUrl = ("workspaces/{0}/dataPipelines" -f $WorkspaceId) + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $DataPipelineName } @@ -69,13 +69,13 @@ function New-FabricDataPipeline Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Create DataPipeline")) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create DataPipeline")) { - # Step 4: Make the API request + # Make the API request $apiParams = @{ - Uri = $apiEndpointURI - method = 'Post' - body = $bodyJson + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson } $response = Invoke-FabricRestMethod @apiParams } @@ -84,7 +84,7 @@ function New-FabricDataPipeline } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create DataPipeline. Error: $errorDetails" -Level Error } diff --git a/source/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 b/src/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 similarity index 83% rename from source/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 rename to src/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 index c6bda6b5..42ada62a 100644 --- a/source/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 +++ b/src/Public/Data Pipeline/Remove-FabricDataPipeline.ps1 @@ -43,15 +43,17 @@ function Remove-FabricDataPipeline Confirm-TokenState # Construct the API URI - $apiEndpointURI = "workspaces/{0}/dataPipelines/{1}" -f $WorkspaceId, $DataPipelineId - Write-Message -Message "API Endpoint: $apiEndpointURI" -Level Debug + $apiEndpointUrl = "workspaces/{0}/dataPipelines/{1}" -f $WorkspaceId, $DataPipelineId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Delete DataPipeline")) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Delete DataPipeline")) { # Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Delete + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + } + $response = Invoke-FabricRestMethod @apiParams } Write-Message -Message "DataPipeline '$DataPipelineId' deleted successfully from workspace '$WorkspaceId'." -Level Info return $response diff --git a/source/Public/Data Pipeline/Update-FabricDataPipeline.ps1 b/src/Public/Data Pipeline/Update-FabricDataPipeline.ps1 similarity index 87% rename from source/Public/Data Pipeline/Update-FabricDataPipeline.ps1 rename to src/Public/Data Pipeline/Update-FabricDataPipeline.ps1 index c4732e89..1e6cf47f 100644 --- a/source/Public/Data Pipeline/Update-FabricDataPipeline.ps1 +++ b/src/Public/Data Pipeline/Update-FabricDataPipeline.ps1 @@ -58,8 +58,8 @@ function Update-FabricDataPipeline Confirm-TokenState # Construct the API URL - $apiEndpointURI = "workspaces/{0}/dataPipelines/{1}" -f $WorkspaceId, $DataPipelineId - Write-Message -Message "API Endpoint: $apiEndpointURI" -Level Debug + $apiEndpointUrl = "workspaces/{0}/dataPipelines/{1}" -f $WorkspaceId, $DataPipelineId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug # Construct the request body $body = @{ @@ -75,13 +75,15 @@ function Update-FabricDataPipeline $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Update DataPipeline")) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update DataPipeline")) { # Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Patch ` - -Body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + } + $response = Invoke-FabricRestMethod @apiParams } Write-Message -Message "DataPipeline '$DataPipelineName' updated successfully!" -Level Info diff --git a/source/Public/Datamart/Get-FabricDatamart.ps1 b/src/Public/Datamart/Get-FabricDatamart.ps1 similarity index 78% rename from source/Public/Datamart/Get-FabricDatamart.ps1 rename to src/Public/Datamart/Get-FabricDatamart.ps1 index 10485a85..5d50205e 100644 --- a/source/Public/Datamart/Get-FabricDatamart.ps1 +++ b/src/Public/Datamart/Get-FabricDatamart.ps1 @@ -37,39 +37,39 @@ function Get-FabricDatamart { [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] - [guid]$datamartId, + [guid]$DatamartId, [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] - [string]$datamartName + [string]$DatamartName ) try { - # Step 2: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 3: Initialize variables + # Initialize variables - $apiEndpointURI = "workspaces/{0}/Datamarts" -f $WorkspaceId + $apiEndpointUrl = "workspaces/{0}/datamarts" -f $WorkspaceId $apiParams = @{ - Uri = $apiEndpointURI + Uri = $apiEndpointUrl method = 'Get' } $Datamarts = Invoke-FabricRestMethod @apiParams - # Step 9: Filter results based on provided parameters + # Filter results based on provided parameters - $response = if ($datamartId) { - $Datamarts | Where-Object { $_.Id -eq $datamartId } - } elseif ($datamartName) { - $Datamarts | Where-Object { $_.DisplayName -eq $datamartName } + $response = 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 + # Handle results if ($response) { Write-Message -Message "Datamart found matching the specified criteria." -Level Debug return $response @@ -78,7 +78,7 @@ function Get-FabricDatamart { return $null } } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve Datamart. Error: $errorDetails" -Level Error } diff --git a/src/Public/Dataset/Get-FabricDataset.ps1 b/src/Public/Dataset/Get-FabricDataset.ps1 new file mode 100644 index 00000000..e7f80b40 --- /dev/null +++ b/src/Public/Dataset/Get-FabricDataset.ps1 @@ -0,0 +1,127 @@ +function Get-FabricDataset { + <# + .SYNOPSIS + Retrieves one or more Power BI datasets from My Workspace or a specific workspace. + + .DESCRIPTION + Calls the Power BI REST API to list datasets. + When `GroupId` is supplied the request targets a specific workspace + (`groups/{groupId}/datasets`); otherwise it targets My Workspace (`datasets`). + + Optionally filter the results to a single dataset by `DatasetId` or `DatasetName`. + + .PARAMETER WorkspaceId + (Optional) The unique identifier of the workspace to query. + When omitted, datasets from My Workspace are returned. + + .PARAMETER DatasetId + (Optional) The unique identifier of a specific dataset to return. + Cannot be combined with `DatasetName`. + + .PARAMETER DatasetName + (Optional) The display name of a specific dataset to return. + Cannot be combined with `DatasetId`. + + .EXAMPLE + Retrieves all datasets from My Workspace. + + ```powershell + Get-FabricDataset + ``` + + .EXAMPLE + Retrieves all datasets from a specific workspace. + + ```powershell + Get-FabricDataset -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" + ``` + + .EXAMPLE + Retrieves a specific dataset by name from a workspace. + + ```powershell + Get-FabricDataset -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" -DatasetName "Sales Model" + ``` + + .EXAMPLE + Retrieves a specific dataset by ID from My Workspace. + + ```powershell + Get-FabricDataset -DatasetId "12345678-90ab-cdef-1234-567890abcdef" + ``` + + .NOTES + - Requires a valid Power BI / Fabric token (call `Connect-FabricAccount` first). + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + - Callers with Read-only access to a workspace may receive a limited response + (only `id` and `name` fields) from the in-group endpoint. + + Author: Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [Alias('GroupId')] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$DatasetId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DatasetName + ) + + try { + # Handle ambiguous input + if ($DatasetId -and $DatasetName) { + Write-Message -Message "Both 'DatasetId' and 'DatasetName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Build the endpoint path depending on whether a workspace (group) is specified + if ($PSBoundParameters.ContainsKey('WorkspaceId')) { + $apiEndpointUrl = "groups/{0}/datasets" -f $WorkspaceId + } else { + $apiEndpointUrl = "datasets" + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + PowerBIApi = $true + TypeName = 'Dataset' + HandleResponse = $true + ExtractValue = 'True' + } + $datasets = @(Invoke-FabricRestMethod @apiParams) + + # Filter results based on provided parameters + $result = if ($DatasetId) { + $datasets | Where-Object { $_.id -eq $DatasetId } + } elseif ($DatasetName) { + $datasets | Where-Object { $_.name -eq $DatasetName } + } else { + Write-Message -Message "No filter provided. Returning all datasets." -Level Debug + $datasets + } + + if ($result) { + Write-Message -Message "Retrieved $(@($result).Count) dataset(s)." -Level Debug + return $result + } else { + Write-Message -Message "No dataset found matching the provided criteria." -Level Warning + return $null + } + } catch { + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve datasets. Error: $errorDetails" -Level Error + } +} diff --git a/src/Public/Dataset/Get-FabricDatasetRefreshHistory.ps1 b/src/Public/Dataset/Get-FabricDatasetRefreshHistory.ps1 new file mode 100644 index 00000000..612dbf70 --- /dev/null +++ b/src/Public/Dataset/Get-FabricDatasetRefreshHistory.ps1 @@ -0,0 +1,105 @@ +function Get-FabricDatasetRefreshHistory { + <# + .SYNOPSIS + Retrieves the refresh history of a Power BI dataset. + + .DESCRIPTION + Calls the Power BI REST API to retrieve the refresh history for a specified dataset. + When `GroupId` is supplied the request targets the dataset inside a specific workspace + (`groups/{groupId}/datasets/{datasetId}/refreshes`); otherwise it targets the dataset + in My Workspace (`datasets/{datasetId}/refreshes`). + + .PARAMETER DatasetId + (Mandatory) The unique identifier of the dataset whose refresh history to retrieve. + + .PARAMETER WorkspaceId + (Optional) The unique identifier of the workspace that contains the dataset. + When omitted, the My Workspace endpoint is used. + + .PARAMETER Top + (Optional) The number of refresh history entries to return. Must be at least 1. + Defaults to 60 (Power BI API default). + + .EXAMPLE + Retrieves the refresh history for a dataset in My Workspace. + + ```powershell + Get-FabricDatasetRefreshHistory -DatasetId "12345678-90ab-cdef-1234-567890abcdef" + ``` + + .EXAMPLE + Retrieves the last 10 refresh history entries for a dataset in a specific workspace. + + ```powershell + Get-FabricDatasetRefreshHistory ` + -DatasetId "12345678-90ab-cdef-1234-567890abcdef" ` + -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" ` + -Top 10 + ``` + + .NOTES + - Requires a valid Power BI / Fabric token (call `Connect-FabricAccount` first). + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + - OneDrive refresh history is not returned by the Power BI API. + - The API retains at most 60 entries; entries older than 3 days are pruned once more + than 20 exist. + + Author: Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$DatasetId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [Alias('GroupId')] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateRange(1, [int]::MaxValue)] + [int]$Top + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Build the endpoint path depending on whether a workspace (group) is specified + if ($PSBoundParameters.ContainsKey('WorkspaceId')) { + $apiEndpointUrl = "groups/{0}/datasets/{1}/refreshes" -f $WorkspaceId, $DatasetId + } else { + $apiEndpointUrl = "datasets/{0}/refreshes" -f $DatasetId + } + + # Append $top query parameter when requested + if ($PSBoundParameters.ContainsKey('Top')) { + $apiEndpointUrl = "{0}?`$top={1}" -f $apiEndpointUrl, $Top + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + PowerBIApi = $true + TypeName = 'Dataset' + ObjectIdOrName = $DatasetId + HandleResponse = $true + ExtractValue = 'True' + } + $refreshes = Invoke-FabricRestMethod @apiParams + + if ($refreshes) { + Write-Message -Message "Retrieved $($refreshes.Count) refresh history entries for dataset '$DatasetId'." -Level Debug + return $refreshes + } else { + Write-Message -Message "No refresh history found for dataset '$DatasetId'." -Level Warning + return $null + } + } catch { + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve refresh history for dataset '$DatasetId'. Error: $errorDetails" -Level Error + } +} diff --git a/src/Public/Dataset/Invoke-FabricDatasetRefresh.ps1 b/src/Public/Dataset/Invoke-FabricDatasetRefresh.ps1 new file mode 100644 index 00000000..f3ec8671 --- /dev/null +++ b/src/Public/Dataset/Invoke-FabricDatasetRefresh.ps1 @@ -0,0 +1,195 @@ +function Invoke-FabricDatasetRefresh { + <# + .SYNOPSIS + Triggers a refresh of a Power BI dataset. + + .DESCRIPTION + Calls the Power BI REST API to trigger an on-demand refresh for a specified dataset. + When `WorkspaceId` is supplied the request targets the dataset inside a specific workspace + (`groups/{groupId}/datasets/{datasetId}/refreshes`); otherwise it targets the dataset + in My Workspace (`datasets/{datasetId}/refreshes`). + + Providing any parameter beyond `NotifyOption` triggers an enhanced refresh (requires + Premium or Fabric capacity). Shared capacity supports only `NotifyOption` and is + limited to 8 refreshes per day. + + .PARAMETER DatasetId + (Mandatory) The unique identifier of the dataset to refresh. + + .PARAMETER WorkspaceId + (Optional) The unique identifier of the workspace that contains the dataset. + When omitted, the My Workspace endpoint is used. + + .PARAMETER NotifyOption + (Optional) Mail notification preference for the refresh. + Valid values: NoNotification, MailOnFailure, MailOnCompletion. + Defaults to NoNotification. Not applicable to enhanced refreshes or service principal operations. + + .PARAMETER Type + (Optional) The type of processing to perform. + Valid values: Full, ClearValues, Calculate, DataOnly, Automatic, Defragment. + Triggers an enhanced refresh when specified. + + .PARAMETER CommitMode + (Optional) Determines whether objects are committed in batches or only when complete. + Valid values: Transactional, PartialBatch. + Triggers an enhanced refresh when specified. + + .PARAMETER MaxParallelism + (Optional) The maximum number of threads on which to run parallel processing commands. + Triggers an enhanced refresh when specified. + + .PARAMETER RetryCount + (Optional) The number of times the operation is retried before failing. + Triggers an enhanced refresh when specified. + + .PARAMETER Timeout + (Optional) The timeout per individual refresh attempt, in HH:MM:SS format (max 24 hours + total including retries). Defaults to 5 hours. + Triggers an enhanced refresh when specified. + + .PARAMETER EffectiveDate + (Optional) If an incremental refresh policy is applied, overrides the current date used + to determine the rolling window period. + Triggers an enhanced refresh when specified. + + .PARAMETER ApplyRefreshPolicy + (Optional) Whether to apply the configured incremental refresh policy. + Triggers an enhanced refresh when specified. + + .PARAMETER Objects + (Optional) An array of hashtables specifying specific tables and/or partitions to process. + Each entry should contain 'table' and optionally 'partition' keys. + Triggers an enhanced refresh when specified. + + Example: @(@{ table = 'Sales' }, @{ table = 'Date'; partition = 'Date-2024' }) + + .EXAMPLE + Triggers a simple refresh of a dataset in My Workspace. + + ```powershell + Invoke-FabricDatasetRefresh -DatasetId "12345678-90ab-cdef-1234-567890abcdef" + ``` + + .EXAMPLE + Triggers a full refresh of a dataset in a specific workspace with email notification on failure. + + ```powershell + Invoke-FabricDatasetRefresh ` + -DatasetId "12345678-90ab-cdef-1234-567890abcdef" ` + -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" ` + -Type Full ` + -NotifyOption MailOnFailure + ``` + + .EXAMPLE + Triggers an enhanced refresh targeting specific tables only. + + ```powershell + Invoke-FabricDatasetRefresh ` + -DatasetId "12345678-90ab-cdef-1234-567890abcdef" ` + -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" ` + -Objects @(@{ table = 'Sales' }, @{ table = 'Date' }) ` + -CommitMode PartialBatch + ``` + + .NOTES + - Requires a valid Power BI / Fabric token (call `Connect-FabricAccount` first). + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + - The API responds with 202 Accepted; the refresh runs asynchronously in the background. + - Use `Get-FabricDatasetRefreshHistory` to monitor refresh status. + + Author: Kamil Nowinski + #> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$DatasetId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [Alias('GroupId')] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateSet('NoNotification', 'MailOnFailure', 'MailOnCompletion')] + [string]$NotifyOption = 'NoNotification', + + [Parameter(Mandatory = $false)] + [ValidateSet('Full', 'ClearValues', 'Calculate', 'DataOnly', 'Automatic', 'Defragment')] + [string]$Type, + + [Parameter(Mandatory = $false)] + [ValidateSet('Transactional', 'PartialBatch')] + [string]$CommitMode, + + [Parameter(Mandatory = $false)] + [ValidateRange(1, [int]::MaxValue)] + [int]$MaxParallelism, + + [Parameter(Mandatory = $false)] + [ValidateRange(0, [int]::MaxValue)] + [int]$RetryCount, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$Timeout, + + [Parameter(Mandatory = $false)] + [datetime]$EffectiveDate, + + [Parameter(Mandatory = $false)] + [bool]$ApplyRefreshPolicy, + + [Parameter(Mandatory = $false)] + [hashtable[]]$Objects + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Build the endpoint path depending on whether a workspace is specified + if ($PSBoundParameters.ContainsKey('WorkspaceId')) { + $apiEndpointUrl = "groups/{0}/datasets/{1}/refreshes" -f $WorkspaceId, $DatasetId + } else { + $apiEndpointUrl = "datasets/{0}/refreshes" -f $DatasetId + } + + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Build the request body — always include notifyOption + $body = @{ + notifyOption = $NotifyOption + } + + if ($PSBoundParameters.ContainsKey('Type')) { $body.type = $Type } + if ($PSBoundParameters.ContainsKey('CommitMode')) { $body.commitMode = $CommitMode } + if ($PSBoundParameters.ContainsKey('MaxParallelism')) { $body.maxParallelism = $MaxParallelism } + if ($PSBoundParameters.ContainsKey('RetryCount')) { $body.retryCount = $RetryCount } + if ($PSBoundParameters.ContainsKey('Timeout')) { $body.timeout = $Timeout } + if ($PSBoundParameters.ContainsKey('EffectiveDate')) { $body.effectiveDate = $EffectiveDate.ToString('o') } + if ($PSBoundParameters.ContainsKey('ApplyRefreshPolicy')){ $body.applyRefreshPolicy = $ApplyRefreshPolicy } + if ($PSBoundParameters.ContainsKey('Objects')) { $body.objects = $Objects } + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + if ($PSCmdlet.ShouldProcess($DatasetId, "Refresh Dataset")) { + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + PowerBIApi = $true + TypeName = 'Dataset' + ObjectIdOrName = $DatasetId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams + } + } catch { + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to trigger refresh for dataset '$DatasetId'. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Deployment Pipeline/Add-FabricWorkspaceToStage.ps1 b/src/Public/Deployment Pipeline/Add-FabricWorkspaceToStage.ps1 similarity index 91% rename from source/Public/Deployment Pipeline/Add-FabricWorkspaceToStage.ps1 rename to src/Public/Deployment Pipeline/Add-FabricWorkspaceToStage.ps1 index d720b51f..7fc771be 100644 --- a/source/Public/Deployment Pipeline/Add-FabricWorkspaceToStage.ps1 +++ b/src/Public/Deployment Pipeline/Add-FabricWorkspaceToStage.ps1 @@ -52,19 +52,19 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = ("deploymentPipelines/{0}/stages/{1}/assignWorkspace" -f $DeploymentPipelineId, $StageId) Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $requestBody = @{ workspaceId = $WorkspaceId } - # Step 4: Make the API request and validate response + # Make the API request and validate response $apiParameters = @{ Uri = $apiEndpointUrl Method = 'POST' @@ -76,11 +76,11 @@ Author: Kamil Nowinski } $response = Invoke-FabricRestMethod @apiParameters - # Step 5: Return results + # Return results $response } catch { - # Step 6: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to assign workspace to deployment pipeline stage. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipeline.ps1 b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipeline.ps1 similarity index 95% rename from source/Public/Deployment Pipeline/Get-FabricDeploymentPipeline.ps1 rename to src/Public/Deployment Pipeline/Get-FabricDeploymentPipeline.ps1 index d7080a34..9fde5e49 100644 --- a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipeline.ps1 +++ b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipeline.ps1 @@ -48,7 +48,7 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState if ($PSBoundParameters.ContainsKey("DeploymentPipelineName") -and $PSBoundParameters.ContainsKey("DeploymentPipelineId")) @@ -65,7 +65,7 @@ Author: Kamil Nowinski $apiEndpointUrl = "deploymentPipelines" } - # Step 5: Make the API request + # Make the API request $apiParameters = @{ Uri = $apiEndpointUrl Method = 'GET' @@ -81,11 +81,11 @@ Author: Kamil Nowinski $response = $response | Where-Object { $_.displayName -eq $DeploymentPipelineName } } - # Step 7: Handle results + # Handle results $response } catch { - # Step 8: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to retrieve deployment pipelines. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineOperation.ps1 b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineOperation.ps1 similarity index 93% rename from source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineOperation.ps1 rename to src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineOperation.ps1 index 7afefa9a..bcc6818d 100644 --- a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineOperation.ps1 +++ b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineOperation.ps1 @@ -45,13 +45,13 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "deploymentPipelines/$DeploymentPipelineId/operations/$OperationId" - # Step 3: Make the API request + # Make the API request $apiParameters = @{ Uri = $apiEndpointUrl Method = 'GET' @@ -64,7 +64,7 @@ Author: Kamil Nowinski $response } catch { - # Step 6: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to retrieve deployment pipeline operation. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineRoleAssignments.ps1 b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineRoleAssignments.ps1 similarity index 89% rename from source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineRoleAssignments.ps1 rename to src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineRoleAssignments.ps1 index 8405d9c3..5f3ddcd3 100644 --- a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineRoleAssignments.ps1 +++ b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineRoleAssignments.ps1 @@ -33,13 +33,13 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 3: Construct the API URL + # Construct the API URL $apiEndpointUrl = "deploymentPipelines/$DeploymentPipelineId/roleAssignments" - # Step 4: Make the API request and validate response + # Make the API request and validate response $apiParameters = @{ Uri = $apiEndpointUrl Method = 'GET' @@ -49,11 +49,11 @@ Author: Kamil Nowinski } $response = Invoke-FabricRestMethod @apiParameters - # Step 7: Return results + # Return results $response } catch { - # Step 8: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to get deployment pipeline role assignments. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStage.ps1 b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStage.ps1 similarity index 94% rename from source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStage.ps1 rename to src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStage.ps1 index b8021811..7b961e49 100644 --- a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStage.ps1 +++ b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStage.ps1 @@ -52,10 +52,10 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL if ($StageId) { $apiEndpointUrl = "deploymentPipelines/$DeploymentPipelineId/stages/$StageId" } else { @@ -63,7 +63,7 @@ Author: Kamil Nowinski } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Make the API request + # Make the API request $apiParameters = @{ Uri = $apiEndpointUrl Method = 'GET' @@ -77,7 +77,7 @@ Author: Kamil Nowinski $response } catch { - # Step 6: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to retrieve deployment pipeline stage(s). Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStageItem.ps1 b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStageItem.ps1 similarity index 93% rename from source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStageItem.ps1 rename to src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStageItem.ps1 index afaaae82..63d8e985 100644 --- a/source/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStageItem.ps1 +++ b/src/Public/Deployment Pipeline/Get-FabricDeploymentPipelineStageItem.ps1 @@ -46,13 +46,13 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 3: Construct the API URL + # Construct the API URL $apiEndpointUrl = "deploymentPipelines/$DeploymentPipelineId/stages/$StageId/items" - # Step 4: Make the API request + # Make the API request $apiParameters = @{ Uri = $apiEndpointUrl Method = 'GET' @@ -65,7 +65,7 @@ Author: Kamil Nowinski $response } catch { - # Step 8: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to retrieve deployment pipeline stage items. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/New-FabricDeploymentPipeline.ps1 b/src/Public/Deployment Pipeline/New-FabricDeploymentPipeline.ps1 similarity index 92% rename from source/Public/Deployment Pipeline/New-FabricDeploymentPipeline.ps1 rename to src/Public/Deployment Pipeline/New-FabricDeploymentPipeline.ps1 index baf79663..3564ce7b 100644 --- a/source/Public/Deployment Pipeline/New-FabricDeploymentPipeline.ps1 +++ b/src/Public/Deployment Pipeline/New-FabricDeploymentPipeline.ps1 @@ -54,10 +54,10 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Validate stages + # Validate stages foreach ($stage in $Stages) { if (-not $stage.ContainsKey('DisplayName') -or -not $stage.ContainsKey('IsPublic') -or @@ -67,7 +67,7 @@ Author: Kamil Nowinski } } - # Step 3: Construct the request body + # Construct the request body $requestBody = @{ displayName = $DisplayName stages = $Stages @@ -76,7 +76,7 @@ Author: Kamil Nowinski $requestBody.description = $Description } - # Step 4: Make the API request and Validate response + # Make the API request and Validate response if ($PSCmdlet.ShouldProcess("Create new Deployment Pipeline")) { $apiParameters = @{ Uri = "deploymentPipelines" @@ -88,11 +88,11 @@ Author: Kamil Nowinski $response = Invoke-FabricRestMethod @apiParameters } - # Step 5: Handle results + # Handle results $response } catch { - # Step 6: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to create deployment pipeline. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Remove-FabricDeploymentPipeline.ps1 b/src/Public/Deployment Pipeline/Remove-FabricDeploymentPipeline.ps1 similarity index 89% rename from source/Public/Deployment Pipeline/Remove-FabricDeploymentPipeline.ps1 rename to src/Public/Deployment Pipeline/Remove-FabricDeploymentPipeline.ps1 index dcfaf008..508eeb47 100644 --- a/source/Public/Deployment Pipeline/Remove-FabricDeploymentPipeline.ps1 +++ b/src/Public/Deployment Pipeline/Remove-FabricDeploymentPipeline.ps1 @@ -33,14 +33,14 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "deploymentPipelines/$DeploymentPipelineId" Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Make the API request & validate response + # Make the API request & validate response if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Delete Deployment Pipeline")) { $apiParameters = @{ @@ -53,11 +53,11 @@ Author: Kamil Nowinski $response = Invoke-FabricRestMethod @apiParameters } - # Step 4: Handle results + # Handle results $response } catch { - # Step 5: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to delete deployment pipeline. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Remove-FabricWorkspaceFromStage.ps1 b/src/Public/Deployment Pipeline/Remove-FabricWorkspaceFromStage.ps1 similarity index 91% rename from source/Public/Deployment Pipeline/Remove-FabricWorkspaceFromStage.ps1 rename to src/Public/Deployment Pipeline/Remove-FabricWorkspaceFromStage.ps1 index abfd0b5a..f3e96c59 100644 --- a/source/Public/Deployment Pipeline/Remove-FabricWorkspaceFromStage.ps1 +++ b/src/Public/Deployment Pipeline/Remove-FabricWorkspaceFromStage.ps1 @@ -41,14 +41,14 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "deploymentPipelines/$DeploymentPipelineId/stages/$StageId/unassignWorkspace" Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Make the API request and validate response + # Make the API request and validate response if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Workspace from Deployment Pipeline Stage")) { $apiParameters = @{ Uri = $apiEndpointUrl @@ -61,11 +61,11 @@ Author: Kamil Nowinski $response = Invoke-FabricRestMethod @apiParameters } - # Step 4: Return results + # Return results $response } catch { - # Step 5: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to unassign workspace from deployment pipeline stage. Error: $errorDetails" } diff --git a/source/Public/Deployment Pipeline/Start-FabricDeploymentPipelineStage.ps1 b/src/Public/Deployment Pipeline/Start-FabricDeploymentPipelineStage.ps1 similarity index 94% rename from source/Public/Deployment Pipeline/Start-FabricDeploymentPipelineStage.ps1 rename to src/Public/Deployment Pipeline/Start-FabricDeploymentPipelineStage.ps1 index be1cacde..64423388 100644 --- a/source/Public/Deployment Pipeline/Start-FabricDeploymentPipelineStage.ps1 +++ b/src/Public/Deployment Pipeline/Start-FabricDeploymentPipelineStage.ps1 @@ -94,14 +94,14 @@ Author: Kamil Nowinski ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "deploymentPipelines/$DeploymentPipelineId/deploy" Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $requestBody = @{ sourceStageId = $SourceStageId targetStageId = $TargetStageId @@ -115,7 +115,7 @@ Author: Kamil Nowinski $requestBody.note = $Note } - # Step 4: Make the API request and validate response + # Make the API request and validate response if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Start Deployment Pipeline")) { $apiParameters = @{ Uri = $apiEndpointUrl @@ -129,11 +129,11 @@ Author: Kamil Nowinski $response = Invoke-FabricRestMethod @apiParameters } - # Step 5: Return results + # Return results $response } catch { - # Step 6: Error handling + # Error handling $errorDetails = $_.Exception.Message Write-Error -Message "Failed to initiate deployment. Error: $errorDetails" } diff --git a/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentByCapacity.ps1 b/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentByCapacity.ps1 new file mode 100644 index 00000000..33956b32 --- /dev/null +++ b/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentByCapacity.ps1 @@ -0,0 +1,73 @@ +function Add-FabricDomainWorkspaceAssignmentByCapacity { +<# +.SYNOPSIS +Assigns workspaces to a Fabric domain based on specified capacities. + +.DESCRIPTION +The `Add-FabricDomainWorkspaceAssignmentByCapacity` 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 + Assigns workspaces to the domain with ID "12345" based on the specified capacities. + + ```powershell + Add-FabricDomainWorkspaceAssignmentByCapacity -DomainId "12345" -CapacitiesIds @("capacity1", "capacity2") + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding()] + [Alias("Assign-FabricDomainWorkspaceByCapacity")] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid[]]$CapacitiesIds + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}/assignWorkspacesByCapacities" -f $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # 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 + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Assigning domain workspaces by capacity completed successfully!" -Level Info + return $response + } catch { + # 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/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentById.ps1 b/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentById.ps1 similarity index 66% rename from source/Public/Domain/Add-FabricDomainWorkspaceAssignmentById.ps1 rename to src/Public/Domain/Add-FabricDomainWorkspaceAssignmentById.ps1 index a0f9f268..93bae269 100644 --- a/source/Public/Domain/Add-FabricDomainWorkspaceAssignmentById.ps1 +++ b/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentById.ps1 @@ -20,10 +20,9 @@ An array of workspace IDs to be assigned to the domain. This parameter is mandat ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] [Alias("Assign-FabricDomainWorkspaceById")] @@ -38,14 +37,14 @@ Author: Tiago Balabuch ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/admin/domains/{1}/assignWorkspaces" -f $FabricConfig.BaseUrl, $DomainId + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}/assignWorkspaces" -f $DomainId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ workspacesIds = $WorkspaceIds } @@ -54,22 +53,21 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 2 Write-Message -Message "Request Body: $bodyJson" -Level Debug - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams Write-Message -Message "Successfully assigned workspaces to the domain with ID '$DomainId'." -Level Info + return $response + } catch { - # Step 6: Capture and log error details + # 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/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentByPrincipal.ps1 b/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentByPrincipal.ps1 new file mode 100644 index 00000000..0e9dbbdc --- /dev/null +++ b/src/Public/Domain/Add-FabricDomainWorkspaceAssignmentByPrincipal.ps1 @@ -0,0 +1,86 @@ +function Add-FabricDomainWorkspaceAssignmentByPrincipal { +<# +.SYNOPSIS +Assigns workspaces to a domain based on principal IDs in Microsoft Fabric. + +.DESCRIPTION +The `Add-FabricDomainWorkspaceAssignmentByPrincipal` 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 + This example assigns workspaces to a domain using a list of principal IDs and types. + + ```powershell + $PrincipalIds = @( + @{id = "813abb4a-414c-4ac0-9c2c-bd17036fd58c"; type = "User"}, + @{id = "b5b9495c-685a-447a-b4d3-2d8e963e6288"; type = "User"} + ) + + Add-FabricDomainWorkspaceAssignmentByPrincipal -DomainId "12345" -PrincipalIds $PrincipalIds + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding()] + [Alias("Assign-FabricDomainWorkspaceByPrincipal")] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$DomainId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + #[hashtable]$PrincipalIds # Must contain a JSON array of principals with 'id' and 'type' properties + [System.Object]$PrincipalIds + ) + + try { + # 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." + } + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}/assignWorkspacesByPrincipals" -f $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Message + + # 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 + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Assigning domain workspaces by principal completed successfully!" -Level Info + return $response + } catch { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to assign domain workspaces by principals. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Domain/Add-FabricDomainWorkspaceRoleAssignment.ps1 b/src/Public/Domain/Add-FabricDomainWorkspaceRoleAssignment.ps1 similarity index 72% rename from source/Public/Domain/Add-FabricDomainWorkspaceRoleAssignment.ps1 rename to src/Public/Domain/Add-FabricDomainWorkspaceRoleAssignment.ps1 index 2528b00d..f6af3ff6 100644 --- a/source/Public/Domain/Add-FabricDomainWorkspaceRoleAssignment.ps1 +++ b/src/Public/Domain/Add-FabricDomainWorkspaceRoleAssignment.ps1 @@ -27,10 +27,9 @@ An array of principals to assign roles to. Each principal must include: ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] [Alias("Assign-FabricDomainWorkspaceRoleAssignment")] @@ -50,21 +49,21 @@ Author: Tiago Balabuch ) try { - # Step 1: Validate PrincipalIds structure + # 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 + # Ensure token validity Confirm-TokenState - # Step 3: Construct the API URL - $apiEndpointUrl = "{0}/admin/domains/{1}/roleAssignments/bulkAssign" -f $FabricConfig.BaseUrl, $DomainId + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}/roleAssignments/bulkAssign" -f $DomainId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 4: Construct the request body + # Construct the request body $body = @{ type = $DomainRole principals = $PrincipalIds @@ -72,23 +71,22 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 2 Write-Message -Message "Request Body: $bodyJson" -Level Debug - # Step 5: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true } - + $response = Invoke-FabricRestMethod @apiParams Write-Message -Message "Bulk role assignment for domain '$DomainId' completed successfully!" -Level Info + + return $response + } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to bulk assign roles in domain '$DomainId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Domain/Get-FabricDomain.ps1 b/src/Public/Domain/Get-FabricDomain.ps1 similarity index 73% rename from source/Public/Domain/Get-FabricDomain.ps1 rename to src/Public/Domain/Get-FabricDomain.ps1 index d7d9efdd..d2547752 100644 --- a/source/Public/Domain/Get-FabricDomain.ps1 +++ b/src/Public/Domain/Get-FabricDomain.ps1 @@ -30,10 +30,9 @@ The `Get-FabricDomain` function allows retrieval of domains in Microsoft Fabric, ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] @@ -53,42 +52,39 @@ Author: Tiago Balabuch ) try { - # Step 1: Handle ambiguous input + # 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 + # Ensure token validity Confirm-TokenState - # Step 3: Construct the API URL with filtering logic - $apiEndpointUrl = "{0}/admin/domains" -f $FabricConfig.BaseUrl + # Construct the API URL with filtering logic + $apiEndpointUrl = "admin/domains" if ($NonEmptyDomainsOnly) { $apiEndpointUrl = "{0}?nonEmptyOnly=true" -f $apiEndpointUrl } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method 'Get' - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Domain' + ObjectIdOrName = $DomainName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams - # Step 6: Handle empty response + # 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 + # Filter results based on provided parameters $domains = if ($DomainId) { $response.domains | Where-Object { $_.Id -eq $DomainId } } elseif ($DomainName) { @@ -99,7 +95,7 @@ Author: Tiago Balabuch return $response.domains } - # Step 8: Handle results + # Handle results if ($domains) { return $domains } else { @@ -107,7 +103,7 @@ Author: Tiago Balabuch return $null } } catch { - # Step 9: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve environment. Error: $errorDetails" -Level Error } diff --git a/src/Public/Domain/Get-FabricDomainWorkspace.ps1 b/src/Public/Domain/Get-FabricDomainWorkspace.ps1 new file mode 100644 index 00000000..1978b203 --- /dev/null +++ b/src/Public/Domain/Get-FabricDomainWorkspace.ps1 @@ -0,0 +1,63 @@ +function Get-FabricDomainWorkspace { +<# +.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 + Fetches workspaces for the domain with ID "12345". + + ```powershell + Get-FabricDomainWorkspace -DomainId "12345" + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$DomainId + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}/workspaces" -f $DomainId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true + ExtractValue = 'True' + } + $response = Invoke-FabricRestMethod @apiParams + + # Handle empty response + if ($response.Count -eq 0) { + Write-Message -Message "No workspace found for the '$DomainId'." -Level Warning + return $null + } + return $response + + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve domain workspaces. Error: $errorDetails" -Level Error + } +} diff --git a/src/Public/Domain/New-FabricDomain.ps1 b/src/Public/Domain/New-FabricDomain.ps1 new file mode 100644 index 00000000..ad30042d --- /dev/null +++ b/src/Public/Domain/New-FabricDomain.ps1 @@ -0,0 +1,98 @@ +function New-FabricDomain +{ +<# +.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 + Creates a "Finance" domain under the parent domain with ID "12345". + + ```powershell + Add-FabricDomain -DomainName "Finance" -DomainDescription "Finance data domain" -ParentDomainId "12345" + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$DomainName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$DomainDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$ParentDomainId + ) + + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "admin/domains" + 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 + + if ($PSCmdlet.ShouldProcess($DomainName, "Create Domain")) + { + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + } + + Write-Message -Message "Domain '$DomainName' created successfully!" -Level Info + return $response + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create domain. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Domain/Remove-FabricDomain.ps1 b/src/Public/Domain/Remove-FabricDomain.ps1 similarity index 57% rename from source/Public/Domain/Remove-FabricDomain.ps1 rename to src/Public/Domain/Remove-FabricDomain.ps1 index 83e9f376..f002f0c5 100644 --- a/source/Public/Domain/Remove-FabricDomain.ps1 +++ b/src/Public/Domain/Remove-FabricDomain.ps1 @@ -18,10 +18,9 @@ The unique identifier of the domain to be deleted. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess,ConfirmImpact = 'High')] @@ -33,27 +32,24 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/admin/domains/{1}" -f $FabricConfig.BaseUrl, $DomainId + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}" -f $DomainId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Domain")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } - # Step 4: Validate the response code - if ($statusCode -ne 200) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Domain")) { - 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams } Write-Message -Message "Domain '$DomainId' deleted successfully!" -Level Info @@ -61,7 +57,7 @@ Author: Tiago Balabuch } catch { - # Step 5: Log and handle errors + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete domain '$DomainId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Domain/Remove-FabricDomainWorkspaceAssignment.ps1 b/src/Public/Domain/Remove-FabricDomainWorkspaceAssignment.ps1 similarity index 70% rename from source/Public/Domain/Remove-FabricDomainWorkspaceAssignment.ps1 rename to src/Public/Domain/Remove-FabricDomainWorkspaceAssignment.ps1 index 375ad4f8..418c5b0b 100644 --- a/source/Public/Domain/Remove-FabricDomainWorkspaceAssignment.ps1 +++ b/src/Public/Domain/Remove-FabricDomainWorkspaceAssignment.ps1 @@ -29,11 +29,10 @@ The unique identifier of the Fabric domain. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -50,10 +49,9 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL # Determine the API endpoint URL based on the presence of WorkspaceIds $endpointSuffix = if ($WorkspaceIds) { @@ -64,11 +62,10 @@ Author: Tiago Balabuch "unassignAllWorkspaces" } - $apiEndpointUrl = "{0}/admin/domains/{1}/{2}" -f $FabricConfig.BaseUrl, $DomainId, $endpointSuffix + $apiEndpointUrl = "admin/domains/{0}/{1}" -f $DomainId, $endpointSuffix Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - - # Step 3: Construct the request body (if needed) + # Construct the request body (if needed) $bodyJson = if ($WorkspaceIds) { $body = @{ workspacesIds = $WorkspaceIds } @@ -80,28 +77,26 @@ Author: Tiago Balabuch } Write-Message -Message "Request Body: $bodyJson" -Level Debug + if ($PSCmdlet.ShouldProcess($DomainId, "Unassign Workspaces")) { - # Step 4: Make the API request to unassign specific workspaces - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson + # Make the API request to unassign specific workspaces + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams } - # 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 + # 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 } diff --git a/source/Public/Domain/Remove-FabricDomainWorkspaceRoleAssignment.ps1 b/src/Public/Domain/Remove-FabricDomainWorkspaceRoleAssignment.ps1 similarity index 71% rename from source/Public/Domain/Remove-FabricDomainWorkspaceRoleAssignment.ps1 rename to src/Public/Domain/Remove-FabricDomainWorkspaceRoleAssignment.ps1 index ae643341..f7adbe29 100644 --- a/source/Public/Domain/Remove-FabricDomainWorkspaceRoleAssignment.ps1 +++ b/src/Public/Domain/Remove-FabricDomainWorkspaceRoleAssignment.ps1 @@ -27,10 +27,9 @@ An array of principals to assign roles to. Each principal must include: ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -51,21 +50,21 @@ Author: Tiago Balabuch ) try { - # Step 1: Validate PrincipalIds structure + # 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 + # Ensure token validity Confirm-TokenState - # Step 3: Construct the API URL - $apiEndpointUrl = "{0}/admin/domains/{1}/roleAssignments/bulkUnassign" -f $FabricConfig.BaseUrl, $DomainId + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}/roleAssignments/bulkUnassign" -f $DomainId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 4: Construct the request body + # Construct the request body $body = @{ type = $DomainRole principals = $PrincipalIds @@ -73,25 +72,23 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 2 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if($PSCmdlet.ShouldProcess($DomainId, "Unassign Roles")) { - # Step 5: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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 + if ($PSCmdlet.ShouldProcess($DomainId, "Unassign Roles")) { + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams } + Write-Message -Message "Bulk role unassignment for domain '$DomainId' completed successfully!" -Level Info } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to bulk assign roles in domain '$DomainId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Domain/Update-FabricDomain.ps1 b/src/Public/Domain/Update-FabricDomain.ps1 similarity index 71% rename from source/Public/Domain/Update-FabricDomain.ps1 rename to src/Public/Domain/Update-FabricDomain.ps1 index 9f79d1af..a41a9948 100644 --- a/source/Public/Domain/Update-FabricDomain.ps1 +++ b/src/Public/Domain/Update-FabricDomain.ps1 @@ -27,10 +27,9 @@ The new name for the domain. Must be alphanumeric. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -55,14 +54,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/admin/domains/{1}" -f $FabricConfig.BaseUrl, $DomainId + # Construct the API URL + $apiEndpointUrl = "admin/domains/{0}" -f $DomainId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $DomainName } @@ -83,30 +82,25 @@ Author: Tiago Balabuch if ($PSCmdlet.ShouldProcess($DomainName, "Update Domain")) { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Domain' + ObjectIdOrName = $DomainName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams } - # Step 6: Handle results + # Handle results Write-Message -Message "Domain '$DomainName' updated successfully!" -Level Info return $response } catch { - # Step 7: Log and handle errors + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update domain '$DomainId'. Error: $errorDetails" -Level Error } diff --git a/src/Public/Environment/Get-FabricEnvironment.ps1 b/src/Public/Environment/Get-FabricEnvironment.ps1 new file mode 100644 index 00000000..15518ad4 --- /dev/null +++ b/src/Public/Environment/Get-FabricEnvironment.ps1 @@ -0,0 +1,105 @@ +function Get-FabricEnvironment { + + <# +.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 EnvironmentId +(Optional) The ID of a specific environment to retrieve. + +.PARAMETER EnvironmentName +(Optional) The name of the specific environment to retrieve. + +.EXAMPLE + Retrieves the "Development" environment from workspace "12345". + + ```powershell + Get-FabricEnvironment -WorkspaceId "12345" -EnvironmentName "Development" + ``` + +.EXAMPLE + Retrieves all environments in workspace "12345". + + ```powershell + Get-FabricEnvironment -WorkspaceId "12345" + ``` + +.NOTES +- Calls `Confirm-TokenState` 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, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$EnvironmentId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentName + ) + + try { + # Handle ambiguous input + if ($EnvironmentId -and $EnvironmentName) { + Write-Message -Message "Both 'EnvironmentId' and 'EnvironmentName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments" -f $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true + ExtractValue = 'True' + } + $environments = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve environment. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Environment/Get-FabricEnvironmentLibrary.ps1 b/src/Public/Environment/Get-FabricEnvironmentLibrary.ps1 similarity index 62% rename from source/Public/Environment/Get-FabricEnvironmentLibrary.ps1 rename to src/Public/Environment/Get-FabricEnvironmentLibrary.ps1 index 8f24fdd5..4abe7dd6 100644 --- a/source/Public/Environment/Get-FabricEnvironmentLibrary.ps1 +++ b/src/Public/Environment/Get-FabricEnvironmentLibrary.ps1 @@ -22,10 +22,9 @@ The unique identifier of the environment whose libraries are being queried. ``` .NOTES -- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. - Uses `Confirm-TokenState` to validate the token before making API calls. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -39,30 +38,27 @@ Author: Tiago Balabuch ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/libraries" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/libraries" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams - # Step 5: Handle results + # Handle results return $response } catch { - # Step 6: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve environment libraries. Error: $errorDetails" -Level Error } diff --git a/source/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 b/src/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 similarity index 63% rename from source/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 rename to src/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 index 4278710e..463f81f9 100644 --- a/source/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 +++ b/src/Public/Environment/Get-FabricEnvironmentSparkCompute.ps1 @@ -22,10 +22,9 @@ The unique identifier of the environment whose Spark compute details are being r ``` .NOTES -- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. - Uses `Confirm-TokenState` to validate the token before making API calls. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -39,30 +38,27 @@ Author: Tiago Balabuch ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/sparkcompute" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/sparkcompute" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams - # Step 5: Handle results + # Handle results return $response } catch { - # Step 6: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve environment Spark compute. Error: $errorDetails" -Level Error } diff --git a/source/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 b/src/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 similarity index 62% rename from source/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 rename to src/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 index 9f2c5ffa..79b65575 100644 --- a/source/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 +++ b/src/Public/Environment/Get-FabricEnvironmentStagingLibrary.ps1 @@ -21,10 +21,9 @@ The unique identifier of the environment for which staging library details are b ``` .NOTES -- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. - Uses `Confirm-TokenState` to validate the token before making API calls. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -39,30 +38,27 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/libraries" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/staging/libraries" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams - # Step 5: Handle results + # Handle results return $response.customLibraries } catch { - # Step 6: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve environment spark compute. Error: $errorDetails" -Level Error } diff --git a/source/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 b/src/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 similarity index 63% rename from source/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 rename to src/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 index 26ed63f9..5c284ff3 100644 --- a/source/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 +++ b/src/Public/Environment/Get-FabricEnvironmentStagingSparkCompute.ps1 @@ -21,10 +21,9 @@ The unique identifier of the environment for which staging Spark compute details ``` .NOTES -- Requires the `$FabricConfig` global object, including `BaseUrl` and `FabricHeaders`. - Uses `Confirm-TokenState` to validate the token before making API calls. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -39,30 +38,27 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/sparkcompute" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/staging/sparkcompute" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams - # Step 5: Handle results + # Handle results return $response } catch { - # Step 6: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve environment spark compute. Error: $errorDetails" -Level Error } diff --git a/source/Public/Environment/Import-FabricEnvironmentStagingLibrary.ps1 b/src/Public/Environment/Import-FabricEnvironmentStagingLibrary.ps1 similarity index 62% rename from source/Public/Environment/Import-FabricEnvironmentStagingLibrary.ps1 rename to src/Public/Environment/Import-FabricEnvironmentStagingLibrary.ps1 index ef4fc3bd..e7a25e2d 100644 --- a/source/Public/Environment/Import-FabricEnvironmentStagingLibrary.ps1 +++ b/src/Public/Environment/Import-FabricEnvironmentStagingLibrary.ps1 @@ -20,10 +20,9 @@ The unique identifier of the environment where the library will be uploaded. .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 `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] @@ -39,34 +38,30 @@ Author: Tiago Balabuch ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/libraries" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/staging/libraries" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams - # Step 6: Handle results + # Handle results Write-Message -Message "Environment staging library uploaded successfully!" -Level Info return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to upload environment staging library. Error: $errorDetails" -Level Error } diff --git a/src/Public/Environment/New-FabricEnvironment.ps1 b/src/Public/Environment/New-FabricEnvironment.ps1 new file mode 100644 index 00000000..986aae4d --- /dev/null +++ b/src/Public/Environment/New-FabricEnvironment.ps1 @@ -0,0 +1,92 @@ +function New-FabricEnvironment +{ +<# +.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 + Creates an environment named "DevEnv" in workspace "12345" with the specified description. + + ```powershell + Add-FabricEnvironment -WorkspaceId "12345" -EnvironmentName "DevEnv" -EnvironmentDescription "Development Environment" + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentDescription + ) + + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments" -f $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # 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 + + if ($PSCmdlet.ShouldProcess($EnvironmentName, "Create Environment")) + { + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + } + + Write-Message -Message "Environment '$EnvironmentName' created successfully!" -Level Info + return $response + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create environment. Error: $errorDetails" -Level Error + } +} diff --git a/src/Public/Environment/Publish-FabricEnvironment.ps1 b/src/Public/Environment/Publish-FabricEnvironment.ps1 new file mode 100644 index 00000000..486b91bd --- /dev/null +++ b/src/Public/Environment/Publish-FabricEnvironment.ps1 @@ -0,0 +1,65 @@ +function Publish-FabricEnvironment { +<# +.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 + Initiates the publishing process for the specified staging environment. + + ```powershell + Publish-FabricEnvironment -WorkspaceId "workspace-12345" -EnvironmentId "environment-67890" + ``` + +.NOTES +- Uses `Confirm-TokenState` to validate the token before making API calls. + +Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$EnvironmentId + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/staging/publish" -f $WorkspaceId, $EnvironmentId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + + Write-Message -Message "Publish operation request has been submitted successfully for the environment '$EnvironmentId'!" -Level Info + return $response + } catch { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create environment. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Environment/Remove-FabricEnvironment.ps1 b/src/Public/Environment/Remove-FabricEnvironment.ps1 similarity index 63% rename from source/Public/Environment/Remove-FabricEnvironment.ps1 rename to src/Public/Environment/Remove-FabricEnvironment.ps1 index 04d6f762..2829e596 100644 --- a/source/Public/Environment/Remove-FabricEnvironment.ps1 +++ b/src/Public/Environment/Remove-FabricEnvironment.ps1 @@ -21,10 +21,9 @@ The `Remove-FabricEnvironment` function sends a DELETE request to the Fabric API ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -40,34 +39,32 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Environment")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams } - # 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 + # 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/source/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 b/src/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 similarity index 63% rename from source/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 rename to src/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 index 4847d2d4..7d72a74c 100644 --- a/source/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 +++ b/src/Public/Environment/Remove-FabricEnvironmentStagingLibrary.ps1 @@ -25,10 +25,10 @@ The name of the library to be deleted from the environment. ``` .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 + +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -48,34 +48,31 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/libraries?libraryToDelete={3}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId, $LibraryName + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/staging/libraries?libraryToDelete={2}" -f $WorkspaceId, $EnvironmentId, $LibraryName Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Staging Library")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Environment' + ObjectIdOrName = $LibraryName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Staging library $LibraryName for the Environment '$EnvironmentId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - # 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 + # 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/source/Public/Environment/Stop-FabricEnvironmentPublish.ps1 b/src/Public/Environment/Stop-FabricEnvironmentPublish.ps1 similarity index 59% rename from source/Public/Environment/Stop-FabricEnvironmentPublish.ps1 rename to src/Public/Environment/Stop-FabricEnvironmentPublish.ps1 index 512cdf90..5593e7e8 100644 --- a/source/Public/Environment/Stop-FabricEnvironmentPublish.ps1 +++ b/src/Public/Environment/Stop-FabricEnvironmentPublish.ps1 @@ -22,10 +22,9 @@ The unique identifier of the environment for which the publish operation is to b ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -41,35 +40,31 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/cancelPublish" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/staging/cancelPublish" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Cancel Publish")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # Step 4: Validate the response code - if ($statusCode -ne 200) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Cancel Publish")) { - 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Publication for environment '$EnvironmentId' has been successfully canceled." -Level Info } - Write-Message -Message "Publication for environment '$EnvironmentId' has been successfully canceled." -Level Info } catch { - # Step 5: Log and handle errors + # 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/source/Public/Environment/Update-FabricEnvironment.ps1 b/src/Public/Environment/Update-FabricEnvironment.ps1 similarity index 68% rename from source/Public/Environment/Update-FabricEnvironment.ps1 rename to src/Public/Environment/Update-FabricEnvironment.ps1 index 873322e4..c7eee7d2 100644 --- a/source/Public/Environment/Update-FabricEnvironment.ps1 +++ b/src/Public/Environment/Update-FabricEnvironment.ps1 @@ -34,10 +34,9 @@ The unique identifier of the workspace where the Environment resides. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +60,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $EnvironmentName } @@ -84,29 +83,23 @@ Author: Tiago Balabuch if ($PSCmdlet.ShouldProcess($EnvironmentId, "Update Environment")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Environment '$EnvironmentName' updated successfully!" -Level Info } - - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Environment. Error: $errorDetails" -Level Error } diff --git a/source/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 b/src/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 similarity index 81% rename from source/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 rename to src/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 index e8b894cc..3dfeba3f 100644 --- a/source/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 +++ b/src/Public/Environment/Update-FabricEnvironmentStagingSparkCompute.ps1 @@ -53,10 +53,9 @@ A hashtable of additional Spark properties to configure. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -116,14 +115,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/environments/{2}/staging/sparkcompute" -f $FabricConfig.BaseUrl, $WorkspaceId, $EnvironmentId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/environments/{1}/staging/sparkcompute" -f $WorkspaceId, $EnvironmentId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ instancePool = @{ name = $InstancePoolName @@ -148,29 +147,24 @@ Author: Tiago Balabuch if ($PSCmdlet.ShouldProcess($EnvironmentId, "Update Environment Staging Spark Compute")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Environment' + ObjectIdOrName = $EnvironmentId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Environment staging Spark compute updated successfully!" -Level Info } - - # Step 6: Handle results - Write-Message -Message "Environment staging Spark compute updated successfully!" -Level Info return $response + } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update environment staging Spark compute. Error: $errorDetails" -Level Error } diff --git a/src/Public/Eventhouse/Get-FabricEventhouse.ps1 b/src/Public/Eventhouse/Get-FabricEventhouse.ps1 new file mode 100644 index 00000000..a12b7490 --- /dev/null +++ b/src/Public/Eventhouse/Get-FabricEventhouse.ps1 @@ -0,0 +1,101 @@ +function Get-FabricEventhouse { + <# + .SYNOPSIS + Retrieves Fabric Eventhouses + + .DESCRIPTION + Retrieves Fabric Eventhouses. Without the EventhouseName or EventhouseID parameter, all Eventhouses are returned. + If you want to retrieve a specific Eventhouse, you can use the EventhouseName or EventhouseID parameter. These + parameters cannot be used together. + + .PARAMETER WorkspaceId + Id of the Fabric Workspace for which the Eventhouses should be retrieved. The value for WorkspaceId is a GUID. + An example of a GUID is '12345678-1234-1234-1234-123456789012'. + + .PARAMETER EventhouseName + The name of the Eventhouse to retrieve. This parameter cannot be used together with EventhouseID. + + .PARAMETER EventhouseId + The Id of the Eventhouse to retrieve. This parameter cannot be used together with EventhouseName. The value for WorkspaceId is a GUID. + An example of a GUID is '12345678-1234-1234-1234-123456789012'. + + .EXAMPLE + This example will give you all Eventhouses in the Workspace. + + ```powershell + Get-FabricEventhouse -WorkspaceId '12345678-1234-1234-1234-123456789012' + ``` + + .EXAMPLE + This example will give you all Information about the Eventhouse with the name 'MyEventhouse'. + + ```powershell + Get-FabricEventhouse -WorkspaceId '12345678-1234-1234-1234-123456789012' -EventhouseName 'MyEventhouse' + ``` + + .EXAMPLE + This example will give you all Information about the Eventhouse with the Id '12345678-1234-1234-1234-123456789012'. + + ```powershell + Get-FabricEventhouse -WorkspaceId '12345678-1234-1234-1234-123456789012' -EventhouseId '12345678-1234-1234-1234-123456789012' + ``` + + .LINK + https://learn.microsoft.com/en-us/rest/api/fabric/eventhouse/items/list-eventhouses?tabs=HTTP + + .NOTES + TODO: Add functionality to list all Eventhouses in the subscription. To do so fetch all workspaces + and then all eventhouses in each workspace. + + Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$EventhouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseName + ) + + # Handle ambiguous input + if ($EventhouseId -and $EventhouseName) { + Write-Message -Message "Both 'EventhouseId' and 'EventhouseName' were provided. Please specify only one." -Level Error + return $null + } + + try { + # Ensure token validity + Confirm-TokenState + + $apiParams = @{ + Uri = "workspaces/$WorkspaceId/eventhouses" + Method = 'Get' + TypeName = 'Eventhouse' + ObjectIdOrName = $EventhouseName + HandleResponse = $true + ExtractValue = 'True' + } + + $eventhouses = Invoke-FabricRestMethod @apiParams + + if ($EventhouseId) { + $eventhouses | Where-Object { $_.Id -eq $EventhouseId } + } elseif ($EventhouseName) { + $eventhouses | Where-Object { $_.DisplayName -eq $EventhouseName } + } else { + $eventhouses + } + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventhouse. Error: $errorDetails" -Level Error + } +} diff --git a/src/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 b/src/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 new file mode 100644 index 00000000..77d4ddfb --- /dev/null +++ b/src/Public/Eventhouse/Get-FabricEventhouseDefinition.ps1 @@ -0,0 +1,78 @@ +function Get-FabricEventhouseDefinition { +<# +.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 + This example retrieves the definition of the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricEventhouseDefinition -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" + ``` + +.EXAMPLE + This example retrieves the definition of the Eventhouse with ID "eventhouse-67890" in the workspace with ID "workspace-12345" in JSON format. + + ```powershell + Get-FabricEventhouseDefinition -WorkspaceId "workspace-12345" -EventhouseId "eventhouse-67890" -EventhouseFormat "json" + ``` + +.NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$EventhouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventhouseFormat + ) + + try { + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "workspaces/$WorkspaceId/eventhouses/$EventhouseId/getDefinition" + if ($EventhouseFormat) { + $uri = "$uri?format=$EventhouseFormat" + } + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Eventhouse' + ObjectIdOrName = $EventhouseId + HandleResponse = $true + } + + Invoke-FabricRestMethod @apiParams + + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventhouse. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Eventhouse/New-FabricEventhouse.ps1 b/src/Public/Eventhouse/New-FabricEventhouse.ps1 similarity index 57% rename from source/Public/Eventhouse/New-FabricEventhouse.ps1 rename to src/Public/Eventhouse/New-FabricEventhouse.ps1 index c849aaa0..78b5b3bb 100644 --- a/source/Public/Eventhouse/New-FabricEventhouse.ps1 +++ b/src/Public/Eventhouse/New-FabricEventhouse.ps1 @@ -32,10 +32,9 @@ function New-FabricEventhouse ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -60,16 +59,16 @@ function New-FabricEventhouse [ValidateNotNullOrEmpty()] [string]$EventhousePathPlatformDefinition ) + try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 } @@ -78,6 +77,7 @@ function New-FabricEventhouse { $body.description = $EventhouseDescription } + if ($EventhousePathDefinition) { $eventhouseEncodedContent = Convert-ToBase64 -filePath $EventhousePathDefinition @@ -112,15 +112,10 @@ function New-FabricEventhouse if (-not [string]::IsNullOrEmpty($eventhouseEncodedPlatformContent)) { - # Initialize definition if it doesn't exist if (-not $body.definition) { - $body.definition = @{ - parts = @() - } + $body.definition = @{ parts = @() } } - - # Add new part to the parts array $body.definition.parts += @{ path = ".platform" payload = $eventhouseEncodedPlatformContent @@ -134,75 +129,28 @@ function New-FabricEventhouse } } - # Convert the body to JSON $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($EventhouseName, "Create Eventhouse")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Eventhouse' + ObjectIdOrName = $EventhouseName + HandleResponse = $true } - 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." - } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Eventhouse '$EventhouseName' created successfully!" -Level Info } + $response } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create Eventhouse. Error: $errorDetails" -Level Error } diff --git a/source/Public/Eventhouse/Remove-FabricEventhouse.ps1 b/src/Public/Eventhouse/Remove-FabricEventhouse.ps1 similarity index 54% rename from source/Public/Eventhouse/Remove-FabricEventhouse.ps1 rename to src/Public/Eventhouse/Remove-FabricEventhouse.ps1 index 1ae781c6..316318e3 100644 --- a/source/Public/Eventhouse/Remove-FabricEventhouse.ps1 +++ b/src/Public/Eventhouse/Remove-FabricEventhouse.ps1 @@ -15,9 +15,6 @@ function Remove-FabricEventhouse .PARAMETER EventhouseId The unique identifier of the Eventhouse to be removed. -.PARAMETER EventhouseName - The name of the Eventhouse to delete. EventhouseId and EventhouseName cannot be used together. - .EXAMPLE This example removes the Eventhouse with ID "eventhouse-67890" from the workspace with ID "workspace-12345". @@ -26,10 +23,9 @@ function Remove-FabricEventhouse ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski .LINK https://learn.microsoft.com/en-us/rest/api/fabric/eventhouse/items/delete-eventhouse?tabs=HTTP @@ -44,37 +40,32 @@ function Remove-FabricEventhouse [ValidateNotNullOrEmpty()] [guid]$EventhouseId ) + try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventhouseId + # Construct the API URL + $apiEndpointUrl = "workspaces/{$WorkspaceId}/eventhouses/{$EventhouseId}" Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Eventhouse")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } - # Step 4: Handle response - if ($statusCode -ne 200) + if ($PSCmdlet.ShouldProcess($EventhouseId, "Remove Eventhouse")) { - 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 - } + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Eventhouse' + ObjectIdOrName = $EventhouseId + HandleResponse = $true + } - Write-Message -Message "Eventhouse '$EventhouseId' deleted successfully from workspace '$WorkspaceId'." -Level Info + Invoke-FabricRestMethod @apiParams + Write-Message -Message "Eventhouse '$EventhouseId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } } - catch - { - # Step 5: Log and handle errors + catch { + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete Eventhouse '$EventhouseId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Eventhouse/Update-FabricEventhouse.ps1 b/src/Public/Eventhouse/Update-FabricEventhouse.ps1 similarity index 64% rename from source/Public/Eventhouse/Update-FabricEventhouse.ps1 rename to src/Public/Eventhouse/Update-FabricEventhouse.ps1 index 90684ed8..fed79a23 100644 --- a/source/Public/Eventhouse/Update-FabricEventhouse.ps1 +++ b/src/Public/Eventhouse/Update-FabricEventhouse.ps1 @@ -28,10 +28,9 @@ function Update-FabricEventhouse ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -52,16 +51,17 @@ function Update-FabricEventhouse [ValidateNotNullOrEmpty()] [string]$EventhouseDescription ) + try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventhouseId + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/eventhouses/$EventhouseId" Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $EventhouseName } @@ -71,36 +71,28 @@ function Update-FabricEventhouse $body.description = $EventhouseDescription } - # Convert the body to JSON $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess("Eventhouse", "Update")) + if ($PSCmdlet.ShouldProcess($EventhouseName, "Update Eventhouse")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Eventhouse' + ObjectIdOrName = $EventhouseName + HandleResponse = $true + } + + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Eventhouse '$EventhouseName' updated successfully!" -Level Info } - - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Eventhouse. Error: $errorDetails" -Level Error } diff --git a/source/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 b/src/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 similarity index 53% rename from source/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 rename to src/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 index 815b874b..43d949fb 100644 --- a/source/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 +++ b/src/Public/Eventhouse/Update-FabricEventhouseDefinition.ps1 @@ -28,10 +28,9 @@ function Update-FabricEventhouseDefinition ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -52,22 +51,19 @@ function Update-FabricEventhouseDefinition [ValidateNotNullOrEmpty()] [string]$EventhousePathPlatformDefinition ) + try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/eventhouses/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $EventhouseId - - #if ($UpdateMetadata -eq $true) { + $apiEndpointUrl = "workspaces/$WorkspaceId/eventhouses/$EventhouseId/updateDefinition" if ($EventhousePathPlatformDefinition) { - $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + $apiEndpointUrl = "$apiEndpointUrl?updateMetadata=true" } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body $body = @{ definition = @{ parts = @() @@ -80,7 +76,6 @@ function Update-FabricEventhouseDefinition if (-not [string]::IsNullOrEmpty($EventhouseEncodedContent)) { - # Add new part to the parts array $body.definition.parts += @{ path = "EventhouseProperties.json" payload = $EventhouseEncodedContent @@ -99,7 +94,6 @@ function Update-FabricEventhouseDefinition $EventhouseEncodedPlatformContent = Convert-ToBase64 -filePath $EventhousePathPlatformDefinition if (-not [string]::IsNullOrEmpty($EventhouseEncodedPlatformContent)) { - # Add new part to the parts array $body.definition.parts += @{ path = ".platform" payload = $EventhouseEncodedPlatformContent @@ -115,67 +109,28 @@ function Update-FabricEventhouseDefinition $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess("Eventhouse", "Update")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # Step 5: Handle and log the response - switch ($statusCode) + if ($PSCmdlet.ShouldProcess($EventhouseId, "Update Eventhouse Definition")) { - 200 - { - Write-Message -Message "Update definition for Eventhouse '$EventhouseId' created successfully!" -Level Info - return $response + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Eventhouse' + ObjectIdOrName = $EventhouseId + HandleResponse = $true } - 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 + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Update definition for Eventhouse '$EventhouseId' completed successfully!" -Level Info + } - $operationResult = Get-FabricLongRunningOperationResult -operationId $operationId - Write-Message -Message "Long Running Operation status: $operationResult" -Level Debug + return $response - 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Eventhouse. Error: $errorDetails" -Level Error } diff --git a/src/Public/Eventstream/Get-FabricEventstream.ps1 b/src/Public/Eventstream/Get-FabricEventstream.ps1 new file mode 100644 index 00000000..072f3e4d --- /dev/null +++ b/src/Public/Eventstream/Get-FabricEventstream.ps1 @@ -0,0 +1,104 @@ +function Get-FabricEventstream { + + + <# +.SYNOPSIS +Retrieves an Eventstream or a list of Eventstreams from a specified workspace in Microsoft Fabric. + +.DESCRIPTION + Retrieves Fabric Eventstreams. Without the EventstreamName or EventstreamID parameter, all Eventstreams are returned. + If you want to retrieve a specific Eventstream, you can use the EventstreamName or EventstreamID parameter. These + parameters cannot be used together. + +.PARAMETER WorkspaceId +(Mandatory) The ID of the workspace to query Eventstreams. + +.PARAMETER EventstreamName +(Optional) The name of the specific Eventstream to retrieve. + +.PARAMETER EventstreamId + The Id of the Eventstream to retrieve. This parameter cannot be used together with EventstreamName. The value for EventstreamId is a GUID. + An example of a GUID is '12345678-1234-1234-1234-123456789012'. + +.EXAMPLE + Retrieves the "Development" Eventstream from workspace "12345". + + ```powershell + Get-FabricEventstream -WorkspaceId "12345" -EventstreamName "Development" + ``` + +.EXAMPLE + Retrieves all Eventstreams in workspace "12345". + + ```powershell + Get-FabricEventstream -WorkspaceId "12345" + ``` + +.NOTES +Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$EventstreamId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamName + ) + + try { + # Handle ambiguous input + if ($EventstreamId -and $EventstreamName) { + Write-Message -Message "Both 'EventstreamId' and 'EventstreamName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/eventstreams" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve Eventstreams + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $eventstreams = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventstream. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 b/src/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 new file mode 100644 index 00000000..92cd802d --- /dev/null +++ b/src/Public/Eventstream/Get-FabricEventstreamDefinition.ps1 @@ -0,0 +1,80 @@ +function Get-FabricEventstreamDefinition { +<# +.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 + Retrieves the definition of the Eventstream with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricEventstreamDefinition -WorkspaceId "12345" -EventstreamId "67890" + ``` + +.EXAMPLE + Retrieves the definitions of all Eventstreams in the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricEventstreamDefinition -WorkspaceId "12345" + ``` + +.NOTES +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$EventstreamId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$EventstreamFormat + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/Eventstreams/$EventstreamId/getDefinition" + if ($EventstreamFormat) { + $apiEndpointUrl = "$apiEndpointUrl?format=$EventstreamFormat" + } + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve Eventstream definition + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + + # Return the definition parts + return $response.definition.parts + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Eventstream. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Eventstream/New-FabricEventstream.ps1 b/src/Public/Eventstream/New-FabricEventstream.ps1 similarity index 62% rename from source/Public/Eventstream/New-FabricEventstream.ps1 rename to src/Public/Eventstream/New-FabricEventstream.ps1 index cbfd36d8..ae9ba457 100644 --- a/source/Public/Eventstream/New-FabricEventstream.ps1 +++ b/src/Public/Eventstream/New-FabricEventstream.ps1 @@ -32,10 +32,9 @@ An optional path to the platform-specific definition (e.g., .platform file) to u ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -63,14 +62,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/eventstreams" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/eventstreams" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $EventstreamName } @@ -141,62 +140,22 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($EventstreamName, "Create Eventstream")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + if ($PSCmdlet.ShouldProcess($EventstreamName, "Create Eventstream")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Eventstream '$EventstreamName' created successfully!" -Level Info + return $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create Eventstream. Error: $errorDetails" -Level Error } diff --git a/source/Public/Eventstream/Remove-FabricEventstream.ps1 b/src/Public/Eventstream/Remove-FabricEventstream.ps1 similarity index 57% rename from source/Public/Eventstream/Remove-FabricEventstream.ps1 rename to src/Public/Eventstream/Remove-FabricEventstream.ps1 index 5f0901ed..79cc4795 100644 --- a/source/Public/Eventstream/Remove-FabricEventstream.ps1 +++ b/src/Public/Eventstream/Remove-FabricEventstream.ps1 @@ -26,10 +26,9 @@ The `Remove-FabricEventstream` function sends a DELETE request to the Fabric API ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Validates token expiration before making the API request. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -46,35 +45,28 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/eventstreams/$EventstreamId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Eventstream")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Eventstream")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Eventstream '$EventstreamId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - # 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 + # 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/source/Public/Eventstream/Update-FabricEventstream.ps1 b/src/Public/Eventstream/Update-FabricEventstream.ps1 similarity index 65% rename from source/Public/Eventstream/Update-FabricEventstream.ps1 rename to src/Public/Eventstream/Update-FabricEventstream.ps1 index 6dc9b041..669537bb 100644 --- a/source/Public/Eventstream/Update-FabricEventstream.ps1 +++ b/src/Public/Eventstream/Update-FabricEventstream.ps1 @@ -34,10 +34,9 @@ The unique identifier of the workspace where the Eventstream resides. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +60,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/eventstreams/$EventstreamId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $EventstreamName } @@ -81,30 +80,23 @@ Author: Tiago Balabuch # Convert the body to JSON $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($EventstreamId, "Update Eventstream")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - # 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 + if ($PSCmdlet.ShouldProcess($EventstreamId, "Update Eventstream")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Eventstream '$EventstreamName' updated successfully!" -Level Info + return $response + } } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Eventstream. Error: $errorDetails" -Level Error } diff --git a/source/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 b/src/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 similarity index 56% rename from source/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 rename to src/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 index 79ee66bc..579fc4ce 100644 --- a/source/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 +++ b/src/Public/Eventstream/Update-FabricEventstreamDefinition.ps1 @@ -39,12 +39,10 @@ Default: `$false`. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` 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 +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -68,19 +66,17 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/eventstreams/$EventstreamId/updateDefinition" + if ($EventstreamPathPlatformDefinition) { + $apiEndpointUrl = "$apiEndpointUrl?updateMetadata=true" } - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ parts = @() @@ -128,66 +124,23 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($EventstreamId, "Update Eventstream")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # 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." + if ($PSCmdlet.ShouldProcess($EventstreamId, "Update Eventstream")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Update definition for Eventstream '$EventstreamId' created successfully!" -Level Info + return $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Eventstream. Error: $errorDetails" -Level Error } diff --git a/source/Public/External Data Share/Get-FabricExternalDataShares.ps1 b/src/Public/External Data Share/Get-FabricExternalDataShares.ps1 similarity index 67% rename from source/Public/External Data Share/Get-FabricExternalDataShares.ps1 rename to src/Public/External Data Share/Get-FabricExternalDataShares.ps1 index e8a57a90..c4ba982c 100644 --- a/source/Public/External Data Share/Get-FabricExternalDataShares.ps1 +++ b/src/Public/External Data Share/Get-FabricExternalDataShares.ps1 @@ -15,10 +15,9 @@ function Get-FabricExternalDataShares { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( ) @@ -28,14 +27,17 @@ function Get-FabricExternalDataShares { # Validate authentication token before proceeding Confirm-TokenState - # Construct the API endpoint URI for retrieving external data shares - Write-Message -Message "Constructing API endpoint URI..." -Level Debug - $apiEndpointURI = "{0}/admin/items/externalDataShares" -f $FabricConfig.BaseUrl, $WorkspaceId - - # Invoke the API request to retrieve external data shares - $externalDataShares = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Get + # Construct the API endpoint URL for retrieving external data shares + $apiEndpointUrl = "admin/items/externalDataShares" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API request to retrieve external data shares + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + HandleResponse = $true + } + $externalDataShares = Invoke-FabricRestMethod @apiParams # Return the retrieved external data shares Write-Message -Message "Successfully retrieved external data shares." -Level Debug diff --git a/source/Public/External Data Share/Revoke-FabricExternalDataShares.ps1 b/src/Public/External Data Share/Revoke-FabricExternalDataShares.ps1 similarity index 66% rename from source/Public/External Data Share/Revoke-FabricExternalDataShares.ps1 rename to src/Public/External Data Share/Revoke-FabricExternalDataShares.ps1 index 678941d5..eae1ec3e 100644 --- a/source/Public/External Data Share/Revoke-FabricExternalDataShares.ps1 +++ b/src/Public/External Data Share/Revoke-FabricExternalDataShares.ps1 @@ -25,10 +25,9 @@ function Revoke-FabricExternalDataShares { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -47,25 +46,26 @@ function Revoke-FabricExternalDataShares { try { - # Step 2: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 4: Loop to retrieve all capacities with continuation token - Write-Message -Message "Constructing API endpoint URI..." -Level Debug - $apiEndpointURI = "admin/workspaces/{0}/items/{1}/externalDataShares/{2}/revoke" -f $WorkspaceId, $ItemId, $ExternalDataShareId + # Construct the API endpoint URL + $apiEndpointUrl = "admin/workspaces/$WorkspaceId/items/$ItemId/externalDataShares/$ExternalDataShareId/revoke" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess("$ExternalDataShareId", "revoke")) { - - $externalDataShares = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Post + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $externalDataShares = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Successfully revoked external data shares." -Level Info + return $externalDataShares } - - # Step 4: Return retrieved data - Write-Message -Message "Successfully revoked external data shares." -Level Info - return $externalDataShares } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve External Data Shares. Error: $errorDetails" -Level Error } diff --git a/source/Public/Get-FabricAPIClusterURI.ps1 b/src/Public/Get-FabricAPIClusterURI.ps1 similarity index 100% rename from source/Public/Get-FabricAPIClusterURI.ps1 rename to src/Public/Get-FabricAPIClusterURI.ps1 diff --git a/source/Public/Get-FabricAuthToken.ps1 b/src/Public/Get-FabricAuthToken.ps1 similarity index 100% rename from source/Public/Get-FabricAuthToken.ps1 rename to src/Public/Get-FabricAuthToken.ps1 diff --git a/source/Public/Get-FabricConnection.ps1 b/src/Public/Get-FabricConnection.ps1 similarity index 100% rename from source/Public/Get-FabricConnection.ps1 rename to src/Public/Get-FabricConnection.ps1 diff --git a/source/Public/Get-FabricDatasetRefreshes.ps1 b/src/Public/Get-FabricDatasetRefreshes.ps1 similarity index 87% rename from source/Public/Get-FabricDatasetRefreshes.ps1 rename to src/Public/Get-FabricDatasetRefreshes.ps1 index 7e8ef22b..04c1754a 100644 --- a/source/Public/Get-FabricDatasetRefreshes.ps1 +++ b/src/Public/Get-FabricDatasetRefreshes.ps1 @@ -9,14 +9,14 @@ function Get-FabricDatasetRefreshes { .PARAMETER DatasetID The ID of the dataset. This is a mandatory parameter. - .PARAMETER workspaceId + .PARAMETER WorkspaceId The ID of the workspace. This is a mandatory parameter. .EXAMPLE This command retrieves the refresh history of the specified dataset in the specified workspace. ```powershell - Get-FabricDatasetRefreshes -DatasetID "12345678-90ab-cdef-1234-567890abcdef" -workspaceId "abcdef12-3456-7890-abcd-ef1234567890" + Get-FabricDatasetRefreshes -DatasetId "12345678-90ab-cdef-1234-567890abcdef" -WorkspaceId "abcdef12-3456-7890-abcd-ef1234567890" ``` .INPUTS @@ -32,13 +32,13 @@ function Get-FabricDatasetRefreshes { # Define a mandatory parameter for the dataset ID. Param ( [Parameter(Mandatory = $true)] - [guid]$DatasetID, + [guid]$DatasetId, [Parameter(Mandatory = $true)] - [guid]$workspaceId + [guid]$WorkspaceId ) # Get the dataset information. - $di = Get-PowerBIDataset -id $DatasetID -WorkspaceId $workspaceId + $di = Get-PowerBIDataset -id $DatasetId -WorkspaceId $WorkspaceId # Check if the dataset is refreshable. if ($di.isrefreshable -eq "True") { @@ -48,7 +48,7 @@ function Get-FabricDatasetRefreshes { # Create a PSCustomObject with the information about the refresh. $refresh = [PSCustomObject]@{ Clock = Get-Date - WorkspaceId = $workspaceId + WorkspaceId = $WorkspaceId Workspace = $w.name DatasetId = $di.Id Dataset = $di.Name diff --git a/source/Public/Get-FabricDebugInfo.ps1 b/src/Public/Get-FabricDebugInfo.ps1 similarity index 100% rename from source/Public/Get-FabricDebugInfo.ps1 rename to src/Public/Get-FabricDebugInfo.ps1 diff --git a/source/Public/Get-FabricUsageMetricsQuery.ps1 b/src/Public/Get-FabricUsageMetricsQuery.ps1 similarity index 100% rename from source/Public/Get-FabricUsageMetricsQuery.ps1 rename to src/Public/Get-FabricUsageMetricsQuery.ps1 diff --git a/source/Public/Invoke-FabricRestMethod.ps1 b/src/Public/Invoke-FabricRestMethod.ps1 similarity index 99% rename from source/Public/Invoke-FabricRestMethod.ps1 rename to src/Public/Invoke-FabricRestMethod.ps1 index 87c0af5b..448a4fb7 100644 --- a/source/Public/Invoke-FabricRestMethod.ps1 +++ b/src/Public/Invoke-FabricRestMethod.ps1 @@ -90,7 +90,7 @@ Function Invoke-FabricRestMethod { [switch] $NoWait = $false, [Parameter(Mandatory = $false)] - [switch] $HandleResponse, + [switch] $HandleResponse = $true, [Parameter(Mandatory = $false)] [ValidateSet('True', 'False', 'Auto')] diff --git a/source/Public/Item/Export-FabricItem.ps1 b/src/Public/Item/Export-FabricItem.ps1 similarity index 100% rename from source/Public/Item/Export-FabricItem.ps1 rename to src/Public/Item/Export-FabricItem.ps1 diff --git a/source/Public/Item/Get-FabricItem.ps1 b/src/Public/Item/Get-FabricItem.ps1 similarity index 100% rename from source/Public/Item/Get-FabricItem.ps1 rename to src/Public/Item/Get-FabricItem.ps1 diff --git a/source/Public/Item/Import-FabricItem.ps1 b/src/Public/Item/Import-FabricItem.ps1 similarity index 100% rename from source/Public/Item/Import-FabricItem.ps1 rename to src/Public/Item/Import-FabricItem.ps1 diff --git a/source/Public/Item/Remove-FabricItem.ps1 b/src/Public/Item/Remove-FabricItem.ps1 similarity index 100% rename from source/Public/Item/Remove-FabricItem.ps1 rename to src/Public/Item/Remove-FabricItem.ps1 diff --git a/src/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 b/src/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 new file mode 100644 index 00000000..703bf92c --- /dev/null +++ b/src/Public/KQL Dashboard/Get-FabricKQLDashboard.ps1 @@ -0,0 +1,100 @@ +function Get-FabricKQLDashboard { +<# +.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 KQLDashboardId +(Optional) The ID of the specific KQLDashboard to retrieve. + +.PARAMETER KQLDashboardName +(Optional) The name of the specific KQLDashboard to retrieve. + +.EXAMPLE + Retrieves the "Development" KQLDashboard from workspace "12345". .PARAMETER KQLDashboardID The Id of the KQLDashboard to retrieve. This parameter cannot be used together with KQLDashboardName. The value for KQLDashboardID is a GUID. An example of a GUID is '12345678-1234-1234-1234-123456789012'. + + ```powershell + Get-FabricKQLDashboard -WorkspaceId "12345" -KQLDashboardName "Development" + ``` + +.EXAMPLE + Retrieves all KQLDashboards in workspace "12345". + + ```powershell + Get-FabricKQLDashboard -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$KQLDashboardId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardName + ) + + try { + # Handle ambiguous input + if ($KQLDashboardId -and $KQLDashboardName) { + Write-Message -Message "Both 'KQLDashboardId' and 'KQLDashboardName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDashboards" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'KQL Dashboard' + HandleResponse = $true + ExtractValue = 'True' + } + $KQLDashboards = @(Invoke-FabricRestMethod @apiParams) + + # Filter results based on provided parameters + $KQLDashboard = if ($KQLDashboardId) { + $KQLDashboards | Where-Object { $_.Id -eq $KQLDashboardId } + } elseif ($KQLDashboardName) { + $KQLDashboards | Where-Object { $_.DisplayName -eq $KQLDashboardName } + } else { + Write-Message -Message "No filter provided. Returning all KQLDashboards." -Level Debug + $KQLDashboards + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDashboard. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 b/src/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 new file mode 100644 index 00000000..675cfdde --- /dev/null +++ b/src/Public/KQL Dashboard/Get-FabricKQLDashboardDefinition.ps1 @@ -0,0 +1,83 @@ +function Get-FabricKQLDashboardDefinition { +<# +.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 + Retrieves the definition of the KQLDashboard with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricKQLDashboardDefinition -WorkspaceId "12345" -KQLDashboardId "67890" + ``` + +.EXAMPLE + Retrieves the definitions of all KQLDashboards in the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricKQLDashboardDefinition -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$KQLDashboardId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDashboardFormat + ) + + try { + # Ensure token validity + Confirm-TokenState + + # 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 + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'KQL Dashboard Definition' + ObjectIdOrName = $KQLDashboardId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDashboard. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 b/src/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 similarity index 67% rename from source/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 rename to src/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 index 93f9223d..c5d575a4 100644 --- a/source/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 +++ b/src/Public/KQL Dashboard/New-FabricKQLDashboard.ps1 @@ -42,7 +42,7 @@ An optional path to the platform-specific definition (e.g., .platform file) to u - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -70,14 +70,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $KQLDashboardName } @@ -147,62 +147,24 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($KQLDashboardName, "Create KQLDashboard")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # Step 5: Handle and log the response - switch ($statusCode) + if ($PSCmdlet.ShouldProcess($KQLDashboardName, "Create KQLDashboard")) { - 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'KQL Dashboard' + ObjectIdOrName = $KQLDashboardName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create KQLDashboard. Error: $errorDetails" -Level Error } diff --git a/source/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 b/src/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 similarity index 72% rename from source/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 rename to src/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 index 0cf4d460..b412dd0e 100644 --- a/source/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 +++ b/src/Public/KQL Dashboard/Remove-FabricKQLDashboard.ps1 @@ -24,10 +24,10 @@ The `Remove-FabricKQLDashboard` function sends a DELETE request to the Fabric AP - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]` + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] @@ -40,35 +40,30 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/kqlDashboards/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDashboardId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove KQLDashboard")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'KQL Dashboard' + ObjectIdOrName = $KQLDashboardId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams } - # 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 + # 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/source/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 b/src/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 similarity index 74% rename from source/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 rename to src/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 index 5524fd61..59746624 100644 --- a/source/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 +++ b/src/Public/KQL Dashboard/Update-FabricKQLDashboard.ps1 @@ -37,7 +37,7 @@ The unique identifier of the workspace where the KQLDashboard exists. - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +61,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $KQLDashboardName } @@ -84,29 +84,22 @@ Author: Tiago Balabuch if ($PSCmdlet.ShouldProcess($KQLDashboardId, "Update KQLDashboard")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'KQL Dashboard' + ObjectIdOrName = $KQLDashboardName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "KQLDashboard '$KQLDashboardName' updated successfully!" -Level Info + $response } - - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update KQLDashboard. Error: $errorDetails" -Level Error } diff --git a/source/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 b/src/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 similarity index 70% rename from source/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 rename to src/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 index 57c0064d..27d114b0 100644 --- a/source/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 +++ b/src/Public/KQL Dashboard/Update-FabricKQLDashboardDefinition.ps1 @@ -41,7 +41,7 @@ The KQLDashboard content can be provided as file paths, and metadata updates can - 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 +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -65,19 +65,19 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/KQLDashboards/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDashboardId if ($KQLDashboardPathPlatformDefinition) { - $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + $apiEndpointUrl += "?updateMetadata=true" } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ format = $null @@ -127,54 +127,23 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($KQLDashboardId, "Update KQLDashboard")) + if ($PSCmdlet.ShouldProcess($KQLDashboardId, "Update KQLDashboard Definition")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'KQL Dashboard Definition' + ObjectIdOrName = $KQLDashboardId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update KQLDashboard. Error: $errorDetails" -Level Error } diff --git a/src/Public/KQL Database/Get-FabricKQLDatabase.ps1 b/src/Public/KQL Database/Get-FabricKQLDatabase.ps1 new file mode 100644 index 00000000..fb59b3ed --- /dev/null +++ b/src/Public/KQL Database/Get-FabricKQLDatabase.ps1 @@ -0,0 +1,100 @@ +function Get-FabricKQLDatabase { + <# +.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 KQLDatabaseId +(Optional) The ID of a specific KQLDatabase to retrieve. + +.PARAMETER KQLDatabaseName +(Optional) The name of the specific KQLDatabase to retrieve. + +.EXAMPLE + Retrieves the "Development" KQLDatabase from workspace "12345". + + ```powershell + Get-FabricKQLDatabase -WorkspaceId "12345" -KQLDatabaseName "Development" + ``` + +.EXAMPLE + Retrieves all KQLDatabases in workspace "12345". + + ```powershell + Get-FabricKQLDatabase -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$KQLDatabaseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseName + ) + + try { + # Handle ambiguous input + if ($KQLDatabaseId -and $KQLDatabaseName) { + Write-Message -Message "Both 'KQLDatabaseId' and 'KQLDatabaseName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'KQL Database' + HandleResponse = $true + ExtractValue = 'True' + } + $KQLDatabases = @(Invoke-FabricRestMethod @apiParams) + + # Filter results based on provided parameters + $KQLDatabase = if ($KQLDatabaseId) { + $KQLDatabases | Where-Object { $_.Id -eq $KQLDatabaseId } + } elseif ($KQLDatabaseName) { + $KQLDatabases | Where-Object { $_.DisplayName -eq $KQLDatabaseName } + } else { + Write-Message -Message "No filter provided. Returning all KQLDatabases." -Level Debug + $KQLDatabases + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 b/src/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 new file mode 100644 index 00000000..6f7d3be0 --- /dev/null +++ b/src/Public/KQL Database/Get-FabricKQLDatabaseDefinition.ps1 @@ -0,0 +1,83 @@ +function Get-FabricKQLDatabaseDefinition { +<# +.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 + Retrieves the definition of the KQLDatabase with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricKQLDatabaseDefinition -WorkspaceId "12345" -KQLDatabaseId "67890" + ``` + +.EXAMPLE + Retrieves the definitions of all KQLDatabases in the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricKQLDatabaseDefinition -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$KQLDatabaseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLDatabaseFormat + ) + + try { + # Ensure token validity + Confirm-TokenState + + # 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 + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'KQL Database Definition' + ObjectIdOrName = $KQLDatabaseId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLDatabase. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/KQL Database/New-FabricKQLDatabase.ps1 b/src/Public/KQL Database/New-FabricKQLDatabase.ps1 similarity index 76% rename from source/Public/KQL Database/New-FabricKQLDatabase.ps1 rename to src/Public/KQL Database/New-FabricKQLDatabase.ps1 index 0326c12e..ee295b61 100644 --- a/source/Public/KQL Database/New-FabricKQLDatabase.ps1 +++ b/src/Public/KQL Database/New-FabricKQLDatabase.ps1 @@ -57,7 +57,7 @@ An optional path to the platform-specific definition (e.g., .platform file) to u - CreationPayload is evaluate only if Definition file is not provided. - invitationToken has priority over all other payload fields. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -110,14 +110,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body ### This is working $body = @{ displayName = $KQLDatabaseName } @@ -137,8 +137,6 @@ Author: Tiago Balabuch if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedContent)) { - - # Add new part to the parts array $body.definition.parts += @{ path = "DatabaseProperties.json" @@ -158,7 +156,6 @@ Author: Tiago Balabuch if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedPlatformContent)) { - # Add new part to the parts array $body.definition.parts += @{ path = ".platform" @@ -171,15 +168,14 @@ Author: Tiago Balabuch 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" @@ -193,7 +189,6 @@ Author: Tiago Balabuch return $null } } - } else { @@ -247,7 +242,6 @@ Author: Tiago Balabuch { if ($KQLInvitationToken) { - $body.creationPayload.invitationToken = $KQLInvitationToken } if ($KQLSourceClusterUri -and -not $KQLInvitationToken) @@ -259,75 +253,28 @@ Author: Tiago Balabuch $body.creationPayload.sourceDatabaseName = $KQLSourceDatabaseName } } - - } $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($KQLDatabaseName, "Create KQLDatabase")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # Step 5: Handle and log the response - switch ($statusCode) + if ($PSCmdlet.ShouldProcess($KQLDatabaseName, "Create KQLDatabase")) { - 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'KQL Database' + ObjectIdOrName = $KQLDatabaseName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create KQLDatabase. Error: $errorDetails" -Level Error } diff --git a/source/Public/KQL Database/Remove-FabricKQLDatabase.ps1 b/src/Public/KQL Database/Remove-FabricKQLDatabase.ps1 similarity index 67% rename from source/Public/KQL Database/Remove-FabricKQLDatabase.ps1 rename to src/Public/KQL Database/Remove-FabricKQLDatabase.ps1 index 17e4c058..72cfff98 100644 --- a/source/Public/KQL Database/Remove-FabricKQLDatabase.ps1 +++ b/src/Public/KQL Database/Remove-FabricKQLDatabase.ps1 @@ -24,7 +24,7 @@ The `Remove-FabricKQLDatabase` function sends a DELETE request to the Fabric API - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -40,36 +40,30 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDatabaseId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove KQLDatabase")) { - # Step 3: Check if the API endpoint is valid - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'KQL Database' + ObjectIdOrName = $KQLDatabaseId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams } - # 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 + # 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/source/Public/KQL Database/Update-FabricKQLDatabase.ps1 b/src/Public/KQL Database/Update-FabricKQLDatabase.ps1 similarity index 71% rename from source/Public/KQL Database/Update-FabricKQLDatabase.ps1 rename to src/Public/KQL Database/Update-FabricKQLDatabase.ps1 index 6ad947bd..8a2d8e6d 100644 --- a/source/Public/KQL Database/Update-FabricKQLDatabase.ps1 +++ b/src/Public/KQL Database/Update-FabricKQLDatabase.ps1 @@ -37,7 +37,7 @@ The new name for the KQLDatabase. - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +61,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $KQLDatabaseName } @@ -81,32 +81,25 @@ Author: Tiago Balabuch # Convert the body to JSON $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($KQLDatabaseId, "Update KQLDatabase")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - # Step 5: Validate the response code - if ($statusCode -ne 200) + if ($PSCmdlet.ShouldProcess($KQLDatabaseId, "Update KQLDatabase")) { - 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'KQL Database' + ObjectIdOrName = $KQLDatabaseName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "KQLDatabase '$KQLDatabaseName' updated successfully!" -Level Info + $response } - - # Step 6: Handle results - Write-Message -Message "KQLDatabase '$KQLDatabaseName' updated successfully!" -Level Info - return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update KQLDatabase. Error: $errorDetails" -Level Error } diff --git a/source/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 b/src/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 similarity index 65% rename from source/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 rename to src/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 index 419b8906..13832025 100644 --- a/source/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 +++ b/src/Public/KQL Database/Update-FabricKQLDatabaseDefinition.ps1 @@ -47,7 +47,7 @@ Default: `$false`. - 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 +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -72,21 +72,22 @@ Author: Tiago Balabuch [ValidateNotNullOrEmpty()] [string]$KQLDatabasePathSchemaDefinition ) + try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/kqlDatabases/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLDatabaseId if ($KQLDatabasePathPlatformDefinition) { - $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + $apiEndpointUrl += "?updateMetadata=true" } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ parts = @() @@ -138,7 +139,6 @@ Author: Tiago Balabuch if (-not [string]::IsNullOrEmpty($KQLDatabaseEncodedSchemaContent)) { - # Add new part to the parts array $body.definition.parts += @{ path = "DatabaseSchema.kql" @@ -156,67 +156,23 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($KQLDatabaseId, "Update KQLDatabase")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # Step 5: Handle and log the response - switch ($statusCode) + if ($PSCmdlet.ShouldProcess($KQLDatabaseId, "Update KQLDatabase Definition")) { - 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'KQL Database Definition' + ObjectIdOrName = $KQLDatabaseId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update KQLDatabase. Error: $errorDetails" -Level Error } diff --git a/src/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 b/src/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 new file mode 100644 index 00000000..fedc372a --- /dev/null +++ b/src/Public/KQL Queryset/Get-FabricKQLQueryset.ps1 @@ -0,0 +1,101 @@ +function Get-FabricKQLQueryset { + <# +.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 KQLQuerysetId +(Optional) The ID of a specific KQLQueryset to retrieve. + +.PARAMETER KQLQuerysetName +(Optional) The name of the specific KQLQueryset to retrieve. + +.EXAMPLE + Retrieves the "Development" KQLQueryset from workspace "12345". + + ```powershell + Get-FabricKQLQueryset -WorkspaceId "12345" -KQLQuerysetName "Development" + ``` + +.EXAMPLE + Retrieves all KQLQuerysets in workspace "12345". + + ```powershell + Get-FabricKQLQueryset -WorkspaceId "12345" + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$KQLQuerysetId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetName + ) + + try { + # Handle ambiguous input + if ($KQLQuerysetId -and $KQLQuerysetName) { + Write-Message -Message "Both 'KQLQuerysetId' and 'KQLQuerysetName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/kqlQuerysets" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve KQL Querysets + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $KQLQuerysets = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLQueryset. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 b/src/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 new file mode 100644 index 00000000..86ecc2f5 --- /dev/null +++ b/src/Public/KQL Queryset/Get-FabricKQLQuerysetDefinition.ps1 @@ -0,0 +1,81 @@ +function Get-FabricKQLQuerysetDefinition { +<# +.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 + Retrieves the definition of the KQLQueryset with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricKQLQuerysetDefinition -WorkspaceId "12345" -KQLQuerysetId "67890" + ``` + +.EXAMPLE + Retrieves the definitions of all KQLQuerysets in the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricKQLQuerysetDefinition -WorkspaceId "12345" + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$KQLQuerysetId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$KQLQuerysetFormat + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/kqlQuerysets/$KQLQuerysetId/getDefinition" + + if ($KQLQuerysetFormat) { + $apiEndpointUrl = "$apiEndpointUrl?format=$KQLQuerysetFormat" + } + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "KQLQueryset '$KQLQuerysetId' definition retrieved successfully!" -Level Debug + return $response.definition.parts + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve KQLQueryset. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/KQL Queryset/Invoke-FabricKQLCommand.ps1 b/src/Public/KQL Queryset/Invoke-FabricKQLCommand.ps1 similarity index 100% rename from source/Public/KQL Queryset/Invoke-FabricKQLCommand.ps1 rename to src/Public/KQL Queryset/Invoke-FabricKQLCommand.ps1 diff --git a/source/Public/KQL Queryset/New-FabricKQLQueryset.ps1 b/src/Public/KQL Queryset/New-FabricKQLQueryset.ps1 similarity index 62% rename from source/Public/KQL Queryset/New-FabricKQLQueryset.ps1 rename to src/Public/KQL Queryset/New-FabricKQLQueryset.ps1 index 695fb9dc..987774cb 100644 --- a/source/Public/KQL Queryset/New-FabricKQLQueryset.ps1 +++ b/src/Public/KQL Queryset/New-FabricKQLQueryset.ps1 @@ -31,10 +31,9 @@ An optional path to the platform-specific definition (e.g., .platform file) to u ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +60,14 @@ Author: Tiago Balabuch ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/kqlQuerysets" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $KQLQuerysetName } @@ -129,51 +128,19 @@ Author: Tiago Balabuch Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($KQLQuerysetName, "Create KQLQueryset")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "KQLQueryset '$KQLQuerysetName' created successfully!" -Level Info + return $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create KQLQueryset. Error: $errorDetails" -Level Error } diff --git a/source/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 b/src/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 similarity index 51% rename from source/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 rename to src/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 index fcf0907c..56495e84 100644 --- a/source/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 +++ b/src/Public/KQL Queryset/Remove-FabricKQLQueryset.ps1 @@ -21,10 +21,9 @@ The `Remove-FabricKQLQueryset` function sends a DELETE request to the Fabric API ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Validates token expiration before making the API request. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -40,33 +39,28 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove KQLQueryset")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/kqlQuerysets/$KQLQuerysetId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove KQLQueryset")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "KQLQueryset '$KQLQuerysetId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - Write-Message -Message "KQLQueryset '$KQLQuerysetId' deleted successfully from workspace '$WorkspaceId'." -Level Info } catch { - # Step 5: Log and handle errors + # 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/source/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 b/src/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 similarity index 65% rename from source/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 rename to src/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 index 164745a8..787aab51 100644 --- a/source/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 +++ b/src/Public/KQL Queryset/Update-FabricKQLQueryset.ps1 @@ -34,10 +34,9 @@ The unique identifier of the workspace where the KQLQueryset exists. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +60,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/kqlQuerysets/$KQLQuerysetId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $KQLQuerysetName } @@ -81,31 +80,23 @@ Author: Tiago Balabuch # Convert the body to JSON $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($KQLQuerysetId, "Update KQLQueryset")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - # 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 + if ($PSCmdlet.ShouldProcess($KQLQuerysetId, "Update KQLQueryset")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "KQLQueryset '$KQLQuerysetName' updated successfully!" -Level Info + return $response } - - # Step 6: Handle results - Write-Message -Message "KQLQueryset '$KQLQuerysetName' updated successfully!" -Level Info - return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update KQLQueryset. Error: $errorDetails" -Level Error } diff --git a/source/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 b/src/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 similarity index 66% rename from source/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 rename to src/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 index 4b06a2df..e472550b 100644 --- a/source/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 +++ b/src/Public/KQL Queryset/Update-FabricKQLQuerysetDefinition.ps1 @@ -34,12 +34,11 @@ The KQLQueryset content can be provided as file paths, and metadata updates can ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` 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 +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -62,18 +61,18 @@ Author: Tiago Balabuch ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/kqlQuerysets/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $KQLQuerysetId + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/kqlQuerysets/$KQLQuerysetId/updateDefinition" if ($KQLQuerysetPathPlatformDefinition) { - $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + $apiEndpointUrl = "$apiEndpointUrl?updateMetadata=true" } - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ format = $null @@ -116,43 +115,19 @@ Author: Tiago Balabuch Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($KQLQuerysetId, "Update KQLQueryset")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Update definition for KQLQueryset '$KQLQuerysetId' created successfully!" -Level Info + return $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update KQLQueryset. Error: $errorDetails" -Level Error } diff --git a/src/Public/Lakehouse/Get-FabricLakehouse.ps1 b/src/Public/Lakehouse/Get-FabricLakehouse.ps1 new file mode 100644 index 00000000..04f93483 --- /dev/null +++ b/src/Public/Lakehouse/Get-FabricLakehouse.ps1 @@ -0,0 +1,99 @@ +function Get-FabricLakehouse { + <# +.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 LakehouseId +(Optional) The ID of a specific Lakehouse to retrieve. + +.PARAMETER LakehouseName +(Optional) The name of the specific Lakehouse to retrieve. + +.EXAMPLE + Retrieves the "Development" Lakehouse from workspace "12345". + + ```powershell + Get-FabricLakehouse -WorkspaceId "12345" -LakehouseName "Development" + ``` + +.EXAMPLE + Retrieves all Lakehouses in workspace "12345". + + ```powershell + Get-FabricLakehouse -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$LakehouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$LakehouseName + ) + + try { + # Handle ambiguous input + if ($LakehouseId -and $LakehouseName) { + Write-Message -Message "Both 'LakehouseId' and 'LakehouseName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "workspaces/{0}/lakehouses" -f $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Lakehouse' + HandleResponse = $true + ExtractValue = 'True' + } + $lakehouses = @(Invoke-FabricRestMethod @apiParams) + + # Filter results based on provided parameters + $lakehouses = if ($LakehouseId) { + $lakehouses | Where-Object { $_.Id -eq $LakehouseId } + } elseif ($LakehouseName) { + $lakehouses | Where-Object { $_.DisplayName -eq $LakehouseName } + } else { + Write-Message -Message "No filter provided. Returning all Lakehouses." -Level Debug + $lakehouses + } + + if ($lakehouses) { + Write-Message -Message "Lakehouse found matching the specified criteria." -Level Debug + return $lakehouses + } else { + Write-Message -Message "No Lakehouse found matching the provided criteria." -Level Warning + return $null + } + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Lakehouse. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Lakehouse/Get-FabricLakehouseTable.ps1 b/src/Public/Lakehouse/Get-FabricLakehouseTable.ps1 new file mode 100644 index 00000000..54bd099d --- /dev/null +++ b/src/Public/Lakehouse/Get-FabricLakehouseTable.ps1 @@ -0,0 +1,69 @@ +function Get-FabricLakehouseTable { + + <# +.SYNOPSIS +Retrieves tables from a specified Lakehouse in a Fabric workspace. + +.DESCRIPTION +This function retrieves tables from a specified Lakehouse in a Fabric workspace. It handles pagination using a continuation token to ensure all data is retrieved. + +.PARAMETER WorkspaceId +The ID of the workspace containing the Lakehouse. + +.PARAMETER LakehouseId +The ID of the Lakehouse from which to retrieve tables. + +.EXAMPLE + This example retrieves all tables from the specified Lakehouse in the specified workspace. + + ```powershell + Get-FabricLakehouseTable -WorkspaceId "your-workspace-id" -LakehouseId "your-lakehouse-id" + ``` + +.NOTES + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + [OutputType([System.Object[]])] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$LakehouseId + ) + + try { + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "workspaces/{0}/lakehouses/{1}/tables" -f $WorkspaceId, $LakehouseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Table list endpoint returns .data instead of .value; collect per-page response objects + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Lakehouse Table' + HandleResponse = $true + } + $tables = @(Invoke-FabricRestMethod @apiParams) | ForEach-Object { $_.data } + + 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Lakehouse. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Lakehouse/New-FabricLakehouse.ps1 b/src/Public/Lakehouse/New-FabricLakehouse.ps1 similarity index 51% rename from source/Public/Lakehouse/New-FabricLakehouse.ps1 rename to src/Public/Lakehouse/New-FabricLakehouse.ps1 index ca2b4232..1dbeb1a2 100644 --- a/source/Public/Lakehouse/New-FabricLakehouse.ps1 +++ b/src/Public/Lakehouse/New-FabricLakehouse.ps1 @@ -32,7 +32,7 @@ An optional path to enable schemas in the Lakehouse - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -56,14 +56,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $LakehouseName } @@ -83,59 +83,21 @@ Author: Tiago Balabuch Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($LakehouseName, "Create Lakehouse")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Lakehouse' + ObjectIdOrName = $LakehouseName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create Lakehouse. Error: $errorDetails" -Level Error } diff --git a/source/Public/Lakehouse/Remove-FabricLakehouse.ps1 b/src/Public/Lakehouse/Remove-FabricLakehouse.ps1 similarity index 55% rename from source/Public/Lakehouse/Remove-FabricLakehouse.ps1 rename to src/Public/Lakehouse/Remove-FabricLakehouse.ps1 index 69aced7f..63dbd295 100644 --- a/source/Public/Lakehouse/Remove-FabricLakehouse.ps1 +++ b/src/Public/Lakehouse/Remove-FabricLakehouse.ps1 @@ -21,10 +21,9 @@ The `Remove-FabricLakehouse` function sends a DELETE request to the Fabric API t ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. -- Validates token expiration before making the API request. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -40,34 +39,28 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/lakehouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $LakehouseId + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/lakehouses/$LakehouseId" Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Lakehouse")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Lakehouse' + ObjectIdOrName = $LakehouseId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams } - # 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 + # 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/source/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 b/src/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 similarity index 69% rename from source/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 rename to src/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 index a460ac8d..808ab984 100644 --- a/source/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 +++ b/src/Public/Lakehouse/Start-FabricLakehouseTableMaintenance.ps1 @@ -60,7 +60,7 @@ function Start-FabricLakehouseTableMaintenance - The function uses the `Get-FabricLongRunningOperation` function to check the status of long-running operations. - The function uses the `Invoke-RestMethod` cmdlet to make API requests. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -107,10 +107,9 @@ function Start-FabricLakehouseTableMaintenance try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - $lakehouse = Get-FabricLakehouse -WorkspaceId $WorkspaceId -LakehouseId $LakehouseId if ($lakehouse.properties.PSObject.Properties['defaultSchema'] -and -not $SchemaName) { @@ -118,11 +117,11 @@ function Start-FabricLakehouseTableMaintenance return } - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ executionData = @{ tableName = $TableName @@ -150,11 +149,8 @@ function Start-FabricLakehouseTableMaintenance $body.executionData.optimizeSettings.zOrderBy = $ColumnsZOrderBy } - - if ($retentionPeriod) { - if (-not $body.executionData.PSObject.Properties['vacuumSettings']) { $body.executionData.vacuumSettings = @{ @@ -162,71 +158,28 @@ function Start-FabricLakehouseTableMaintenance } } $body.executionData.vacuumSettings.retentionPeriod = $retentionPeriod - } $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Start Table Maintenance Job")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Lakehouse Table Maintenance' + ObjectIdOrName = $LakehouseId + NoWait = (-not $waitForCompletion) + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to start table maintenance job. Error: $errorDetails" -Level Error } diff --git a/source/Public/Lakehouse/Update-FabricLakehouse.ps1 b/src/Public/Lakehouse/Update-FabricLakehouse.ps1 similarity index 65% rename from source/Public/Lakehouse/Update-FabricLakehouse.ps1 rename to src/Public/Lakehouse/Update-FabricLakehouse.ps1 index ca45be8d..b79a5d30 100644 --- a/source/Public/Lakehouse/Update-FabricLakehouse.ps1 +++ b/src/Public/Lakehouse/Update-FabricLakehouse.ps1 @@ -34,10 +34,9 @@ The new name for the Lakehouse. ``` .NOTES -- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +60,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/lakehouses/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $LakehouseId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/lakehouses/{1}" -f $WorkspaceId, $LakehouseId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $LakehouseName } @@ -83,30 +82,21 @@ Author: Tiago Balabuch Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($LakehouseId, "Update Lakehouse")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Lakehouse' + ObjectIdOrName = $LakehouseName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + $response } - - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Lakehouse. Error: $errorDetails" -Level Error } diff --git a/source/Public/Lakehouse/Write-FabricLakehouseTableData.ps1 b/src/Public/Lakehouse/Write-FabricLakehouseTableData.ps1 similarity index 62% rename from source/Public/Lakehouse/Write-FabricLakehouseTableData.ps1 rename to src/Public/Lakehouse/Write-FabricLakehouseTableData.ps1 index a7812b71..c76ebff9 100644 --- a/source/Public/Lakehouse/Write-FabricLakehouseTableData.ps1 +++ b/src/Public/Lakehouse/Write-FabricLakehouseTableData.ps1 @@ -55,7 +55,7 @@ function Write-FabricLakehouseTableData .NOTES - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -107,14 +107,14 @@ function Write-FabricLakehouseTableData try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ relativePath = $RelativePath pathType = $PathType @@ -137,65 +137,22 @@ function Write-FabricLakehouseTableData if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Load Lakehouse Table Data")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Lakehouse Table' + ObjectIdOrName = $TableName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } - # Step 6: Handle results - } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Lakehouse. Error: $errorDetails" -Level Error } diff --git a/src/Public/ML Experiment/Get-FabricMLExperiment.ps1 b/src/Public/ML Experiment/Get-FabricMLExperiment.ps1 new file mode 100644 index 00000000..22640847 --- /dev/null +++ b/src/Public/ML Experiment/Get-FabricMLExperiment.ps1 @@ -0,0 +1,99 @@ +function Get-FabricMLExperiment { +<# +.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 + This example retrieves the ML Experiment details for the experiment with ID "experiment-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentId "experiment-67890" + ``` + +.EXAMPLE + This example retrieves the ML Experiment details for the experiment named "My ML Experiment" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentName "My ML Experiment" + ``` + +.NOTES + Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$MLExperimentId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentName + ) + + try { + # Handle ambiguous input + if ($MLExperimentId -and $MLExperimentName) { + Write-Message -Message "Both 'MLExperimentId' and 'MLExperimentName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlExperiments" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve ML Experiments + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $MLExperiments = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve ML Experiment. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/ML Experiment/New-FabricMLExperiment.ps1 b/src/Public/ML Experiment/New-FabricMLExperiment.ps1 new file mode 100644 index 00000000..a6ef8e57 --- /dev/null +++ b/src/Public/ML Experiment/New-FabricMLExperiment.ps1 @@ -0,0 +1,88 @@ +function New-FabricMLExperiment +{ +<# +.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 + This example creates a new ML Experiment named "New ML Experiment" in the workspace with ID "workspace-12345" with the provided description. + + ```powershell + New-FabricMLExperiment -WorkspaceId "workspace-12345" -MLExperimentName "New ML Experiment" -MLExperimentDescription "Description of the new ML Experiment" + ``` + +.NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLExperimentDescription + ) + + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlExperiments" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # 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 + + if ($PSCmdlet.ShouldProcess($MLExperimentName, "Create ML Experiment")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "ML Experiment '$MLExperimentName' created successfully!" -Level Info + return $response + } + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create ML Experiment. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/ML Experiment/Remove-FabricMLExperiment.ps1 b/src/Public/ML Experiment/Remove-FabricMLExperiment.ps1 similarity index 55% rename from source/Public/ML Experiment/Remove-FabricMLExperiment.ps1 rename to src/Public/ML Experiment/Remove-FabricMLExperiment.ps1 index 443c07b2..4145ae62 100644 --- a/source/Public/ML Experiment/Remove-FabricMLExperiment.ps1 +++ b/src/Public/ML Experiment/Remove-FabricMLExperiment.ps1 @@ -22,11 +22,9 @@ function Remove-FabricMLExperiment ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch - + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] param ( @@ -40,35 +38,28 @@ function Remove-FabricMLExperiment ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove ML Experiment")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlExperiments/$MLExperimentId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # 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 + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove ML Experiment")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "ML Experiment '$MLExperimentId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - Write-Message -Message "ML Experiment '$MLExperimentId' deleted successfully from workspace '$WorkspaceId'." -Level Info } catch { - # Step 5: Log and handle errors + # 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/source/Public/ML Experiment/Update-FabricMLExperiment.ps1 b/src/Public/ML Experiment/Update-FabricMLExperiment.ps1 similarity index 64% rename from source/Public/ML Experiment/Update-FabricMLExperiment.ps1 rename to src/Public/ML Experiment/Update-FabricMLExperiment.ps1 index 9c8d7025..ed833f54 100644 --- a/source/Public/ML Experiment/Update-FabricMLExperiment.ps1 +++ b/src/Public/ML Experiment/Update-FabricMLExperiment.ps1 @@ -28,11 +28,9 @@ function Update-FabricMLExperiment ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch - + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -55,14 +53,14 @@ function Update-FabricMLExperiment try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlExperiments/$MLExperimentId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $MLExperimentName } @@ -75,31 +73,23 @@ function Update-FabricMLExperiment # Convert the body to JSON $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($MLExperimentName, "Update ML Experiment")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - # 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 + if ($PSCmdlet.ShouldProcess($MLExperimentName, "Update ML Experiment")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "ML Experiment '$MLExperimentName' updated successfully!" -Level Info + return $response + } } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update ML Experiment. Error: $errorDetails" -Level Error } diff --git a/src/Public/ML Model/Get-FabricMLModel.ps1 b/src/Public/ML Model/Get-FabricMLModel.ps1 new file mode 100644 index 00000000..67633e7d --- /dev/null +++ b/src/Public/ML Model/Get-FabricMLModel.ps1 @@ -0,0 +1,99 @@ +function Get-FabricMLModel { +<# +.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 + This example retrieves the ML Model details for the model with ID "model-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricMLModel -WorkspaceId "workspace-12345" -MLModelId "model-67890" + ``` + +.EXAMPLE + This example retrieves the ML Model details for the model named "My ML Model" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricMLModel -WorkspaceId "workspace-12345" -MLModelName "My ML Model" + ``` + +.NOTES + Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$MLModelId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLModelName + ) + + try { + # Handle ambiguous input + if ($MLModelId -and $MLModelName) { + Write-Message -Message "Both 'MLModelId' and 'MLModelName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlModels" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve ML Models + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $MLModels = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve ML Model. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/ML Model/New-FabricMLModel.ps1 b/src/Public/ML Model/New-FabricMLModel.ps1 new file mode 100644 index 00000000..ff1cc835 --- /dev/null +++ b/src/Public/ML Model/New-FabricMLModel.ps1 @@ -0,0 +1,88 @@ +function New-FabricMLModel +{ +<# +.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 + This example creates a new ML Model named "New ML Model" in the workspace with ID "workspace-12345" with the provided description. + + ```powershell + New-FabricMLModel -WorkspaceId "workspace-12345" -MLModelName "New ML Model" -MLModelDescription "Description of the new ML Model" + ``` + +.NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$MLModelName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MLModelDescription + ) + + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlModels" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # 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 + + if ($PSCmdlet.ShouldProcess($MLModelName, "Create ML Model")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "ML Model '$MLModelName' created successfully!" -Level Info + return $response + } + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create ML Model. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/ML Model/Remove-FabricMLModel.ps1 b/src/Public/ML Model/Remove-FabricMLModel.ps1 similarity index 54% rename from source/Public/ML Model/Remove-FabricMLModel.ps1 rename to src/Public/ML Model/Remove-FabricMLModel.ps1 index 41fd3ed5..637274d7 100644 --- a/source/Public/ML Model/Remove-FabricMLModel.ps1 +++ b/src/Public/ML Model/Remove-FabricMLModel.ps1 @@ -22,11 +22,9 @@ function Remove-FabricMLModel ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch - + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -40,34 +38,28 @@ function Remove-FabricMLModel ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove ML Model")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlModels/$MLModelId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove ML Model")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "ML Model '$MLModelId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - Write-Message -Message "ML Model '$MLModelId' deleted successfully from workspace '$WorkspaceId'." -Level Info } catch { - # Step 5: Log and handle errors + # 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/source/Public/ML Model/Update-FabricMLModel.ps1 b/src/Public/ML Model/Update-FabricMLModel.ps1 similarity index 59% rename from source/Public/ML Model/Update-FabricMLModel.ps1 rename to src/Public/ML Model/Update-FabricMLModel.ps1 index 17a88818..1d24d37a 100644 --- a/source/Public/ML Model/Update-FabricMLModel.ps1 +++ b/src/Public/ML Model/Update-FabricMLModel.ps1 @@ -25,11 +25,9 @@ function Update-FabricMLModel ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch - + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -48,14 +46,14 @@ function Update-FabricMLModel try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/mlModels/$MLModelId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ description = $MLModelDescription } @@ -63,31 +61,23 @@ function Update-FabricMLModel # Convert the body to JSON $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update ML Model")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - # 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 + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update ML Model")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "ML Model '$MLModelId' updated successfully!" -Level Info + return $response + } } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update ML Model. Error: $errorDetails" -Level Error } diff --git a/src/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 b/src/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 new file mode 100644 index 00000000..5b82bb2e --- /dev/null +++ b/src/Public/Mirrored Database/Get-FabricMirroredDatabase.ps1 @@ -0,0 +1,100 @@ +function Get-FabricMirroredDatabase { + <# +.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 MirroredDatabaseId +(Optional) The ID of a specific MirroredDatabase to retrieve. + +.PARAMETER MirroredDatabaseName +(Optional) The name of the specific MirroredDatabase to retrieve. + +.EXAMPLE + Retrieves the "Development" MirroredDatabase from workspace "12345". + + ```powershell + Get-FabricMirroredDatabase -WorkspaceId "12345" -MirroredDatabaseName "Development" + ``` + +.EXAMPLE + Retrieves all MirroredDatabases in workspace "12345". + + ```powershell + Get-FabricMirroredDatabase -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$MirroredDatabaseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredDatabaseName + ) + + try { + # Handle ambiguous input + if ($MirroredDatabaseId -and $MirroredDatabaseName) { + Write-Message -Message "Both 'MirroredDatabaseId' and 'MirroredDatabaseName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Mirrored Database' + HandleResponse = $true + ExtractValue = 'True' + } + $MirroredDatabases = @(Invoke-FabricRestMethod @apiParams) + + # Filter results based on provided parameters + $MirroredDatabase = if ($MirroredDatabaseId) { + $MirroredDatabases | Where-Object { $_.Id -eq $MirroredDatabaseId } + } elseif ($MirroredDatabaseName) { + $MirroredDatabases | Where-Object { $_.DisplayName -eq $MirroredDatabaseName } + } else { + Write-Message -Message "No filter provided. Returning all MirroredDatabases." -Level Debug + $MirroredDatabases + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 b/src/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 new file mode 100644 index 00000000..dc8aaf59 --- /dev/null +++ b/src/Public/Mirrored Database/Get-FabricMirroredDatabaseDefinition.ps1 @@ -0,0 +1,72 @@ +function Get-FabricMirroredDatabaseDefinition { +<# +.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 + Retrieves the definition of the MirroredDatabase with ID `67890` from the workspace with ID `12345`. + + ```powershell + Get-FabricMirroredDatabaseDefinition -WorkspaceId "12345" -MirroredDatabaseId "67890" + ``` + +.EXAMPLE + Retrieves the definitions of all MirroredDatabases in the workspace with ID `12345`. + + ```powershell + Get-FabricMirroredDatabaseDefinition -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$MirroredDatabaseId + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/getDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Mirrored Database Definition' + ObjectIdOrName = $MirroredDatabaseId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 b/src/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 similarity index 68% rename from source/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 rename to src/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 index a98d7333..073544d4 100644 --- a/source/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 +++ b/src/Public/Mirrored Database/Get-FabricMirroredDatabaseStatus.ps1 @@ -24,7 +24,7 @@ function Get-FabricMirroredDatabaseStatus { .NOTES - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] @@ -39,32 +39,25 @@ function Get-FabricMirroredDatabaseStatus { ) try { - # Step 2: Ensure token validity + # Ensure token validity Confirm-TokenState $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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - - # 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Mirrored Database Status' + ObjectIdOrName = $MirroredDatabaseId + HandleResponse = $true } - - # Step 9: Handle results + $response = Invoke-FabricRestMethod @apiParams Write-Message -Message "Returning status of MirroredDatabases." -Level Debug - return $response + $response } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error } diff --git a/src/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 b/src/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 new file mode 100644 index 00000000..af5ad430 --- /dev/null +++ b/src/Public/Mirrored Database/Get-FabricMirroredDatabaseTableStatus.ps1 @@ -0,0 +1,65 @@ +function Get-FabricMirroredDatabaseTableStatus { + <# + + .SYNOPSIS + Retrieves the status of tables in a mirrored database. + + .DESCRIPTION + Retrieves the status of tables in a mirrored database. The function validates the authentication token, constructs the API endpoint URL, and makes a POST request to retrieve the mirroring status of tables. It handles errors and logs messages at various levels (Debug, Error). + + .PARAMETER WorkspaceId + The ID of the workspace containing the mirrored database. + + .PARAMETER MirroredDatabaseId + The ID of the mirrored database whose table status is to be retrieved. + + .EXAMPLE + This example retrieves the status of tables in a mirrored database with the specified ID in the specified workspace. + + ```powershell + Get-FabricMirroredDatabaseTableStatus -WorkspaceId "your-workspace-id" -MirroredDatabaseId "your-mirrored-database-id" + ``` + + .NOTES + The function retrieves the PowerBI access token and makes a POST request to the PowerBI API to retrieve the status of tables in the specified mirrored database. It then returns the 'value' property of the response, which contains the table statuses. + + Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + [OutputType([System.Object[]])] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$MirroredDatabaseId + ) + + try { + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/getTablesMirroringStatus" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # This endpoint returns .data instead of .value + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Mirrored Database Table Status' + ObjectIdOrName = $MirroredDatabaseId + HandleResponse = $true + ExtractValue = 'False' + } + Write-Message -Message "No filter provided. Returning all MirroredDatabases." -Level Debug + @(Invoke-FabricRestMethod @apiParams) | ForEach-Object { $_.data } + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredDatabase. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 b/src/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 similarity index 67% rename from source/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 rename to src/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 index 9e5770ab..fd6dd91d 100644 --- a/source/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 +++ b/src/Public/Mirrored Database/New-FabricMirroredDatabase.ps1 @@ -33,7 +33,7 @@ An optional path to the platform-specific definition (e.g., .platform file) to u - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +61,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $MirroredDatabaseName } @@ -137,61 +137,24 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($MirroredDatabaseName, "Create MirroredDatabase")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # Step 5: Handle and log the response - switch ($statusCode) + if ($PSCmdlet.ShouldProcess($MirroredDatabaseName, "Create MirroredDatabase")) { - 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Mirrored Database' + ObjectIdOrName = $MirroredDatabaseName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create MirroredDatabase. Error: $errorDetails" -Level Error } diff --git a/source/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 b/src/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 similarity index 72% rename from source/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 rename to src/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 index 0f8e2221..beefbfbe 100644 --- a/source/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 +++ b/src/Public/Mirrored Database/Remove-FabricMirroredDatabase.ps1 @@ -24,7 +24,7 @@ The `Remove-FabricMirroredDatabase` function sends a DELETE request to the Fabri - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -39,34 +39,30 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove MirroredDatabase")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Mirrored Database' + ObjectIdOrName = $MirroredDatabaseId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams } - # 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 + # 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/source/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 b/src/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 similarity index 73% rename from source/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 rename to src/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 index f0c8efe3..e93c84c8 100644 --- a/source/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 +++ b/src/Public/Mirrored Database/Start-FabricMirroredDatabaseMirroring.ps1 @@ -28,7 +28,7 @@ function Start-FabricMirroredDatabaseMirroring - Calls `Confirm-TokenState` to ensure token validity before making the API request. - This function handles asynchronous operations and retrieves operation results if required. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -44,36 +44,30 @@ function Start-FabricMirroredDatabaseMirroring try { - # Step 2: Ensure token validity + # Ensure token validity Confirm-TokenState $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/startMirroring" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Start MirroredDatabase Mirroring")) - { - # Step 6: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - } - # Step 7: Validate the response code - if ($statusCode -ne 200) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Start MirroredDatabase Mirroring")) { - 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Mirrored Database Mirroring' + ObjectIdOrName = $MirroredDatabaseId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams } - # 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 + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to start MirroredDatabase. Error: $errorDetails" -Level Error } diff --git a/source/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 b/src/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 similarity index 73% rename from source/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 rename to src/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 index 5af98615..93a46669 100644 --- a/source/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 +++ b/src/Public/Mirrored Database/Stop-FabricMirroredDatabaseMirroring.ps1 @@ -31,7 +31,7 @@ function Stop-FabricMirroredDatabaseMirroring - Calls `Confirm-TokenState` to ensure token validity before making the API request. - This function handles asynchronous operations and retrieves operation results if required. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -47,36 +47,30 @@ function Stop-FabricMirroredDatabaseMirroring try { - # Step 2: Ensure token validity + # Ensure token validity Confirm-TokenState $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/stopMirroring" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Stop MirroredDatabase Mirroring")) - { - # Step 6: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post - } - # Step 7: Validate the response code - if ($statusCode -ne 200) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Stop MirroredDatabase Mirroring")) { - 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Mirrored Database Mirroring' + ObjectIdOrName = $MirroredDatabaseId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams } - # 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 + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to stop MirroredDatabase. Error: $errorDetails" -Level Error } diff --git a/source/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 b/src/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 similarity index 74% rename from source/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 rename to src/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 index c96b8746..c991d332 100644 --- a/source/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 +++ b/src/Public/Mirrored Database/Update-FabricMirroredDatabase.ps1 @@ -37,7 +37,7 @@ The new name for the MirroredDatabase. - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +61,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $MirroredDatabaseName } @@ -81,31 +81,25 @@ Author: Tiago Balabuch # Convert the body to JSON $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($MirroredDatabaseId, "Update MirroredDatabase")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - # Step 5: Validate the response code - if ($statusCode -ne 200) + if ($PSCmdlet.ShouldProcess($MirroredDatabaseId, "Update MirroredDatabase")) { - 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Mirrored Database' + ObjectIdOrName = $MirroredDatabaseName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "MirroredDatabase '$MirroredDatabaseName' updated successfully!" -Level Info + return $response } - - # Step 6: Handle results - Write-Message -Message "MirroredDatabase '$MirroredDatabaseName' updated successfully!" -Level Info - return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update MirroredDatabase. Error: $errorDetails" -Level Error } diff --git a/source/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 b/src/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 similarity index 71% rename from source/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 rename to src/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 index 28de2b08..72a2f203 100644 --- a/source/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 +++ b/src/Public/Mirrored Database/Update-FabricMirroredDatabaseDefinition.ps1 @@ -44,7 +44,7 @@ Default: `$false`. - 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 +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -68,19 +68,19 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/mirroredDatabases/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $MirroredDatabaseId if ($MirroredDatabasePathPlatformDefinition) { - $apiEndpointUrl = "?updateMetadata=true" -f $apiEndpointUrl + $apiEndpointUrl += "?updateMetadata=true" } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ parts = @() @@ -128,54 +128,26 @@ Author: Tiago Balabuch $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($MirroredDatabaseId, "Update MirroredDatabase")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # Step 5: Handle and log the response - switch ($statusCode) + if ($PSCmdlet.ShouldProcess($MirroredDatabaseId, "Update MirroredDatabase Definition")) { - 200 - { - Write-Message -Message "Update definition for MirroredDatabase '$MirroredDatabaseId' created successfully!" -Level Info - return $response + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Mirrored Database Definition' + ObjectIdOrName = $MirroredDatabaseId + HandleResponse = $true } - 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 + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Update definition for MirroredDatabase '$MirroredDatabaseId' created successfully!" -Level Info - $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." - } + return $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update MirroredDatabase. Error: $errorDetails" -Level Error } diff --git a/src/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 b/src/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 new file mode 100644 index 00000000..6a06d47d --- /dev/null +++ b/src/Public/Mirrored Warehouse/Get-FabricMirroredWarehouse.ps1 @@ -0,0 +1,102 @@ +function Get-FabricMirroredWarehouse { + <# +.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 MirroredWarehouseId +(Optional) The ID of a specific MirroredWarehouse to retrieve. + +.PARAMETER MirroredWarehouseName +(Optional) The name of the specific MirroredWarehouse to retrieve. + +.EXAMPLE + Retrieves the "Development" MirroredWarehouse from workspace "12345". + + ```powershell + Get-FabricMirroredWarehouse -WorkspaceId "12345" -MirroredWarehouseName "Development" + ``` + +.EXAMPLE + Retrieves all MirroredWarehouses in workspace "12345". + + ```powershell + Get-FabricMirroredWarehouse -WorkspaceId "12345" + ``` + +.NOTES +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$MirroredWarehouseId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$MirroredWarehouseName + ) + + try { + # Handle ambiguous input + if ($MirroredWarehouseId -and $MirroredWarehouseName) { + Write-Message -Message "Both 'MirroredWarehouseId' and 'MirroredWarehouseName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/MirroredWarehouses" + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $MirroredWarehouses = @(Invoke-FabricRestMethod @apiParams) + + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve MirroredWarehouse. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Notebook/Get-FabricNotebook.ps1 b/src/Public/Notebook/Get-FabricNotebook.ps1 new file mode 100644 index 00000000..cd45a96d --- /dev/null +++ b/src/Public/Notebook/Get-FabricNotebook.ps1 @@ -0,0 +1,99 @@ +function Get-FabricNotebook { + <# +.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 NotebookId +(Optional) The ID of a specific Notebook to retrieve. + +.PARAMETER NotebookName +(Optional) The name of the specific Notebook to retrieve. + +.EXAMPLE + Retrieves the "Development" Notebook from workspace "12345". + + ```powershell + Get-FabricNotebook -WorkspaceId "12345" -NotebookName "Development" + ``` + +.EXAMPLE + Retrieves all Notebooks in workspace "12345". + + ```powershell + Get-FabricNotebook -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$NotebookId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$NotebookName + ) + + try { + # Handle ambiguous input + if ($NotebookId -and $NotebookName) { + Write-Message -Message "Both 'NotebookId' and 'NotebookName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "workspaces/{0}/notebooks" -f $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Notebook' + HandleResponse = $true + ExtractValue = 'True' + } + $notebooks = @(Invoke-FabricRestMethod @apiParams) + + # Filter results based on provided parameters + $notebook = if ($NotebookId) { + $notebooks | Where-Object { $_.Id -eq $NotebookId } + } elseif ($NotebookName) { + $notebooks | Where-Object { $_.DisplayName -eq $NotebookName } + } else { + Write-Message -Message "No filter provided. Returning all Notebooks." -Level Debug + $notebooks + } + + 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Notebook. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Notebook/Get-FabricNotebookDefinition.ps1 b/src/Public/Notebook/Get-FabricNotebookDefinition.ps1 new file mode 100644 index 00000000..afd10756 --- /dev/null +++ b/src/Public/Notebook/Get-FabricNotebookDefinition.ps1 @@ -0,0 +1,89 @@ +function Get-FabricNotebookDefinition { +<# +.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 + Retrieves the definition of the notebook with ID `67890` from the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricNotebookDefinition -WorkspaceId "12345" -NotebookId "67890" + ``` + +.EXAMPLE + Retrieves the definitions of all notebooks in the workspace with ID `12345` in the `ipynb` format. + + ```powershell + Get-FabricNotebookDefinition -WorkspaceId "12345" + ``` + +.NOTES +- Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. +- Calls `Confirm-TokenState` to ensure token validity before making the API request. +- Handles long-running operations asynchronously. + +Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$NotebookId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('ipynb')] + [string]$NotebookFormat = 'ipynb' + ) + + try { + # Ensure token validity + Confirm-TokenState + + # 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 + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Notebook Definition' + ObjectIdOrName = $NotebookId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Notebook. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Notebook/New-FabricNotebook.ps1 b/src/Public/Notebook/New-FabricNotebook.ps1 similarity index 63% rename from source/Public/Notebook/New-FabricNotebook.ps1 rename to src/Public/Notebook/New-FabricNotebook.ps1 index abb735db..35f18a4a 100644 --- a/source/Public/Notebook/New-FabricNotebook.ps1 +++ b/src/Public/Notebook/New-FabricNotebook.ps1 @@ -35,7 +35,7 @@ An optional path to the platform-specific definition (e.g., .platform file) to u - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(supportsShouldProcess)] @@ -63,14 +63,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $NotebookName } @@ -142,64 +142,22 @@ Author: Tiago Balabuch Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($NotebookName, "Create Notebook")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # 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." + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Notebook' + ObjectIdOrName = $NotebookName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create notebook. Error: $errorDetails" -Level Error } diff --git a/source/Public/Notebook/Remove-FabricNotebook.ps1 b/src/Public/Notebook/Remove-FabricNotebook.ps1 similarity index 65% rename from source/Public/Notebook/Remove-FabricNotebook.ps1 rename to src/Public/Notebook/Remove-FabricNotebook.ps1 index c85b4a07..7804b784 100644 --- a/source/Public/Notebook/Remove-FabricNotebook.ps1 +++ b/src/Public/Notebook/Remove-FabricNotebook.ps1 @@ -24,7 +24,7 @@ The `Remove-FabricNotebook` function sends a DELETE request to the Fabric API to - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Validates token expiration before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -40,34 +40,30 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/notebooks/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $NotebookId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Notebook")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Notebook' + ObjectIdOrName = $NotebookId + HandleResponse = $true + } + $result = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Notebook '$NotebookId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - # 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 + # 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/source/Public/Notebook/Update-FabricNotebook.ps1 b/src/Public/Notebook/Update-FabricNotebook.ps1 similarity index 73% rename from source/Public/Notebook/Update-FabricNotebook.ps1 rename to src/Public/Notebook/Update-FabricNotebook.ps1 index 9a6dfd91..00e65bda 100644 --- a/source/Public/Notebook/Update-FabricNotebook.ps1 +++ b/src/Public/Notebook/Update-FabricNotebook.ps1 @@ -37,7 +37,7 @@ The new name for the Notebook. - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. -Author: Tiago Balabuch +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +61,14 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $NotebookName } @@ -83,28 +83,22 @@ Author: Tiago Balabuch Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Notebook")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Notebook' + ObjectIdOrName = $NotebookName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + $response } - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update notebook. Error: $errorDetails" -Level Error } diff --git a/source/Public/Notebook/Update-FabricNotebookDefinition.ps1 b/src/Public/Notebook/Update-FabricNotebookDefinition.ps1 similarity index 61% rename from source/Public/Notebook/Update-FabricNotebookDefinition.ps1 rename to src/Public/Notebook/Update-FabricNotebookDefinition.ps1 index e741e69c..54c6c1d1 100644 --- a/source/Public/Notebook/Update-FabricNotebookDefinition.ps1 +++ b/src/Public/Notebook/Update-FabricNotebookDefinition.ps1 @@ -40,7 +40,7 @@ The notebook content can be provided as file paths, and metadata updates can opt - 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 +Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -64,10 +64,10 @@ Author: Tiago Balabuch try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/notebooks/{2}/updateDefinition" -f $FabricConfig.BaseUrl, $WorkspaceId, $NotebookId if ($NotebookPathPlatformDefinition) @@ -76,7 +76,7 @@ Author: Tiago Balabuch } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ format = "ipynb" @@ -127,66 +127,22 @@ Author: Tiago Balabuch Write-Message -Message "Request Body: $bodyJson" -Level Debug if ($PSCmdlet.ShouldProcess($NotebookId, "Update Notebook Definition")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Notebook Definition' + ObjectIdOrName = $NotebookId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update notebook. Error: $errorDetails" -Level Error } diff --git a/source/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 b/src/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 similarity index 50% rename from source/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 rename to src/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 index 8e1ab41d..29e397b3 100644 --- a/source/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 +++ b/src/Public/Paginated Reports/Get-FabricPaginatedReport.ps1 @@ -34,7 +34,7 @@ function Get-FabricPaginatedReport { - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] @@ -53,85 +53,38 @@ function Get-FabricPaginatedReport { ) try { - # Step 1: Handle ambiguous input + # 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 + # Ensure token validity Confirm-TokenState - # Step 3: Initialize variables - $continuationToken = $null - $PaginatedReports = @() - if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { - Add-Type -AssemblyName System.Web + $apiEndpointUrl = "{0}/workspaces/{1}/paginatedReports" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Paginated Report' + HandleResponse = $true + ExtractValue = 'True' } + $PaginatedReports = @(Invoke-FabricRestMethod @apiParams) - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 + # 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 + # Handle results if ($PaginatedReport) { Write-Message -Message "Paginated Report found matching the specified criteria." -Level Debug return $PaginatedReport @@ -140,7 +93,7 @@ function Get-FabricPaginatedReport { return $null } } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve Paginated Report. Error: $errorDetails" -Level Error } diff --git a/source/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 b/src/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 similarity index 72% rename from source/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 rename to src/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 index fd20c904..a1d06780 100644 --- a/source/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 +++ b/src/Public/Paginated Reports/Update-FabricPaginatedReport.ps1 @@ -31,7 +31,7 @@ function Update-FabricPaginatedReport - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -55,14 +55,14 @@ function Update-FabricPaginatedReport try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $PaginatedReportName } @@ -78,30 +78,22 @@ function Update-FabricPaginatedReport if ($PSCmdlet.ShouldProcess($PaginatedReportName, "Update Paginated Report")) { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - # 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Paginated Report' + ObjectIdOrName = $PaginatedReportName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Paginated Report '$PaginatedReportName' updated successfully!" -Level Info + $response } - - # Step 6: Handle results - Write-Message -Message "Paginated Report '$PaginatedReportName' updated successfully!" -Level Info - return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Paginated Report. Error: $errorDetails" -Level Error } diff --git a/src/Public/Reflex/Get-FabricReflex.ps1 b/src/Public/Reflex/Get-FabricReflex.ps1 new file mode 100644 index 00000000..9e2fbd35 --- /dev/null +++ b/src/Public/Reflex/Get-FabricReflex.ps1 @@ -0,0 +1,100 @@ +function Get-FabricReflex { +<# +.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 + This example retrieves the Reflex details for the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricReflex -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" + ``` + +.EXAMPLE + This example retrieves the Reflex details for the Reflex named "My Reflex" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricReflex -WorkspaceId "workspace-12345" -ReflexName "My Reflex" + ``` + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$ReflexId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexName + ) + try { + # Handle ambiguous input + if ($ReflexId -and $ReflexName) { + Write-Message -Message "Both 'ReflexId' and 'ReflexName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + $apiEndpointUrl = "{0}/workspaces/{1}/reflexes" -f $FabricConfig.BaseUrl, $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + TypeName = 'Reflex' + HandleResponse = $true + ExtractValue = 'True' + } + $Reflexes = @(Invoke-FabricRestMethod @apiParams) + + # Filter results based on provided parameters + $Reflex = if ($ReflexId) { + $Reflexes | Where-Object { $_.Id -eq $ReflexId } + } elseif ($ReflexName) { + $Reflexes | Where-Object { $_.DisplayName -eq $ReflexName } + } else { + Write-Message -Message "No filter provided. Returning all Reflexes." -Level Debug + $Reflexes + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Reflex. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Reflex/Get-FabricReflexDefinition.ps1 b/src/Public/Reflex/Get-FabricReflexDefinition.ps1 new file mode 100644 index 00000000..02313064 --- /dev/null +++ b/src/Public/Reflex/Get-FabricReflexDefinition.ps1 @@ -0,0 +1,81 @@ +function Get-FabricReflexDefinition { +<# +.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 + This example retrieves the definition of the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricReflexDefinition -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" + ``` + +.EXAMPLE + This example retrieves the definition of the Reflex with ID "Reflex-67890" in the workspace with ID "workspace-12345" in JSON format. + + ```powershell + Get-FabricReflexDefinition -WorkspaceId "workspace-12345" -ReflexId "Reflex-67890" -ReflexFormat "json" + ``` + +.NOTES + - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$ReflexId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReflexFormat + ) + try { + # Ensure token validity + Confirm-TokenState + + # 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 + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + TypeName = 'Reflex Definition' + ObjectIdOrName = $ReflexId + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Reflex. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Reflex/New-FabricReflex.ps1 b/src/Public/Reflex/New-FabricReflex.ps1 similarity index 60% rename from source/Public/Reflex/New-FabricReflex.ps1 rename to src/Public/Reflex/New-FabricReflex.ps1 index b390abc7..8626c684 100644 --- a/source/Public/Reflex/New-FabricReflex.ps1 +++ b/src/Public/Reflex/New-FabricReflex.ps1 @@ -34,7 +34,7 @@ function New-FabricReflex - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -61,14 +61,14 @@ function New-FabricReflex ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $ReflexName } @@ -77,6 +77,7 @@ function New-FabricReflex { $body.description = $ReflexDescription } + if ($ReflexPathDefinition) { $ReflexEncodedContent = Convert-ToBase64 -filePath $ReflexPathDefinition @@ -139,69 +140,21 @@ function New-FabricReflex if ($PSCmdlet.ShouldProcess($ReflexName, "Create Reflex")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Reflex' + ObjectIdOrName = $ReflexName + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create Reflex. Error: $errorDetails" -Level Error } diff --git a/source/Public/Reflex/Remove-FabricReflex.ps1 b/src/Public/Reflex/Remove-FabricReflex.ps1 similarity index 69% rename from source/Public/Reflex/Remove-FabricReflex.ps1 rename to src/Public/Reflex/Remove-FabricReflex.ps1 index 572e24f9..2dafd4b2 100644 --- a/source/Public/Reflex/Remove-FabricReflex.ps1 +++ b/src/Public/Reflex/Remove-FabricReflex.ps1 @@ -25,7 +25,7 @@ function Remove-FabricReflex - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] @@ -40,36 +40,30 @@ function Remove-FabricReflex ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/reflexes/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $ReflexId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Reflex")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } - - # 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + TypeName = 'Reflex' + ObjectIdOrName = $ReflexId + HandleResponse = $true + } + Invoke-FabricRestMethod @apiParams } Write-Message -Message "Reflex '$ReflexId' deleted successfully from workspace '$WorkspaceId'." -Level Info } catch { - # Step 5: Log and handle errors + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete Reflex '$ReflexId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Reflex/Update-FabricReflex.ps1 b/src/Public/Reflex/Update-FabricReflex.ps1 similarity index 71% rename from source/Public/Reflex/Update-FabricReflex.ps1 rename to src/Public/Reflex/Update-FabricReflex.ps1 index b10f8927..ee464c8d 100644 --- a/source/Public/Reflex/Update-FabricReflex.ps1 +++ b/src/Public/Reflex/Update-FabricReflex.ps1 @@ -31,7 +31,7 @@ function Update-FabricReflex - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -54,14 +54,14 @@ function Update-FabricReflex ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + # Construct the request body $body = @{ displayName = $ReflexName } @@ -77,30 +77,22 @@ function Update-FabricReflex if ($PSCmdlet.ShouldProcess("Reflex", "Update")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + TypeName = 'Reflex' + ObjectIdOrName = $ReflexName + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Reflex '$ReflexName' updated successfully!" -Level Info + $response } - - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Reflex. Error: $errorDetails" -Level Error } diff --git a/source/Public/Reflex/Update-FabricReflexDefinition.ps1 b/src/Public/Reflex/Update-FabricReflexDefinition.ps1 similarity index 58% rename from source/Public/Reflex/Update-FabricReflexDefinition.ps1 rename to src/Public/Reflex/Update-FabricReflexDefinition.ps1 index 51a4513c..62548979 100644 --- a/source/Public/Reflex/Update-FabricReflexDefinition.ps1 +++ b/src/Public/Reflex/Update-FabricReflexDefinition.ps1 @@ -31,7 +31,7 @@ function Update-FabricReflexDefinition - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -54,20 +54,19 @@ function Update-FabricReflexDefinition ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # 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 + $apiEndpointUrl += "?updateMetadata=true" } Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ parts = @() @@ -118,65 +117,21 @@ function Update-FabricReflexDefinition if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Reflex Definition")) { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - # 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + TypeName = 'Reflex Definition' + ObjectIdOrName = $ReflexId + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Reflex. Error: $errorDetails" -Level Error } diff --git a/src/Public/Report/Get-FabricReport.ps1 b/src/Public/Report/Get-FabricReport.ps1 new file mode 100644 index 00000000..97b16ff8 --- /dev/null +++ b/src/Public/Report/Get-FabricReport.ps1 @@ -0,0 +1,102 @@ +function Get-FabricReport { +<# +.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 + This example retrieves the Report details for the Report with ID "Report-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricReport -WorkspaceId "workspace-12345" -ReportId "Report-67890" + ``` + +.EXAMPLE + This example retrieves the Report details for the Report named "My Report" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricReport -WorkspaceId "workspace-12345" -ReportName "My Report" + ``` + +.NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$ReportId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportName + ) + try { + + # Handle ambiguous input + if ($ReportId -and $ReportName) { + Write-Message -Message "Both 'ReportId' and 'ReportName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/reports" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve Reports + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $Reports = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Report. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Report/Get-FabricReportDefinition.ps1 b/src/Public/Report/Get-FabricReportDefinition.ps1 new file mode 100644 index 00000000..56b3e29d --- /dev/null +++ b/src/Public/Report/Get-FabricReportDefinition.ps1 @@ -0,0 +1,81 @@ +function Get-FabricReportDefinition { +<# +.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 + This example retrieves the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" + ``` + +.EXAMPLE + This example retrieves the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345" in JSON format. + + ```powershell + Get-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" -ReportFormat "json" + ``` + +.NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$ReportId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportFormat + ) + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/reports/$ReportId/getDefinition" + + if ($ReportFormat) { + $apiEndpointUrl = "$apiEndpointUrl?format=$ReportFormat" + } + + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Report '$ReportId' definition retrieved successfully!" -Level Debug + return $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Report. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Report/New-FabricReport.ps1 b/src/Public/Report/New-FabricReport.ps1 new file mode 100644 index 00000000..8b7abbf0 --- /dev/null +++ b/src/Public/Report/New-FabricReport.ps1 @@ -0,0 +1,109 @@ +function New-FabricReport +{ +<# +.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 + An optional path to the folder that contains Report definition files to upload. + + +.EXAMPLE + This example creates a new Report named "New Report" in the workspace with ID "workspace-12345" with the provided description. + + ```powershell + New-FabricReport -WorkspaceId "workspace-12345" -ReportName "New Report" -ReportDescription "Description of the new Report" + ``` + +.NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReportName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$ReportPathDefinition + ) + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/reports" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # 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 + + if ($PSCmdlet.ShouldProcess($ReportName, "Create Report")){ + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Report '$ReportName' created successfully!" -Level Info + return $response + } + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create Report. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Report/Remove-FabricReport.ps1 b/src/Public/Report/Remove-FabricReport.ps1 similarity index 54% rename from source/Public/Report/Remove-FabricReport.ps1 rename to src/Public/Report/Remove-FabricReport.ps1 index 5b179daf..d1b12afb 100644 --- a/source/Public/Report/Remove-FabricReport.ps1 +++ b/src/Public/Report/Remove-FabricReport.ps1 @@ -22,10 +22,9 @@ function Remove-FabricReport ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -40,36 +39,28 @@ function Remove-FabricReport ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/reports/$ReportId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Report")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Report '$ReportId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - - # 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 + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete Report '$ReportId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Report/Update-FabricReport.ps1 b/src/Public/Report/Update-FabricReport.ps1 similarity index 63% rename from source/Public/Report/Update-FabricReport.ps1 rename to src/Public/Report/Update-FabricReport.ps1 index 77e4b47c..01b44265 100644 --- a/source/Public/Report/Update-FabricReport.ps1 +++ b/src/Public/Report/Update-FabricReport.ps1 @@ -28,10 +28,9 @@ function Update-FabricReport ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -54,14 +53,14 @@ function Update-FabricReport ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/reports/$ReportId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $ReportName } @@ -77,30 +76,21 @@ function Update-FabricReport if ($PSCmdlet.ShouldProcess($ReportName, "Update Report")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Report '$ReportName' updated successfully!" -Level Info + return $response } - - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Report. Error: $errorDetails" -Level Error } diff --git a/src/Public/Report/Update-FabricReportDefinition.ps1 b/src/Public/Report/Update-FabricReportDefinition.ps1 new file mode 100644 index 00000000..eabb6a67 --- /dev/null +++ b/src/Public/Report/Update-FabricReportDefinition.ps1 @@ -0,0 +1,113 @@ +function Update-FabricReportDefinition +{ +<# +.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 + This example updates the definition of the Report with ID "Report-67890" in the workspace with ID "workspace-12345" using the provided definition file. + + ```powershell + Update-FabricReportDefinition -WorkspaceId "workspace-12345" -ReportId "Report-67890" -ReportPathDefinition "C:\Path\To\ReportDefinition.json" + ``` + +.NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + +#> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$ReportId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$ReportPathDefinition + ) + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/reports/$ReportId/updateDefinition" + + # 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 = "$apiEndpointUrl?updateMetadata=true" + } + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Report Definition")) + { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Update definition for Report '$ReportId' created successfully!" -Level Info + return $response + } + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update Report. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/SQL Database/Get-FabricSQLDatabase.ps1 b/src/Public/SQL Database/Get-FabricSQLDatabase.ps1 similarity index 100% rename from source/Public/SQL Database/Get-FabricSQLDatabase.ps1 rename to src/Public/SQL Database/Get-FabricSQLDatabase.ps1 diff --git a/source/Public/SQL Database/New-FabricSQLDatabase.ps1 b/src/Public/SQL Database/New-FabricSQLDatabase.ps1 similarity index 92% rename from source/Public/SQL Database/New-FabricSQLDatabase.ps1 rename to src/Public/SQL Database/New-FabricSQLDatabase.ps1 index 053063b4..f7eee7d1 100644 --- a/source/Public/SQL Database/New-FabricSQLDatabase.ps1 +++ b/src/Public/SQL Database/New-FabricSQLDatabase.ps1 @@ -50,14 +50,14 @@ function New-FabricSQLDatabase try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "workspaces/{0}/sqldatabases" -f $WorkspaceId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $Name } @@ -70,7 +70,7 @@ function New-FabricSQLDatabase $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - # Step 4: Make the API request + # Make the API request if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create SQL Database")) { $apiParams = @{ @@ -88,7 +88,7 @@ function New-FabricSQLDatabase } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create SQL Database. Error: $errorDetails" -Level Error } diff --git a/source/Public/SQL Database/Remove-FabricSQLDatabase.ps1 b/src/Public/SQL Database/Remove-FabricSQLDatabase.ps1 similarity index 92% rename from source/Public/SQL Database/Remove-FabricSQLDatabase.ps1 rename to src/Public/SQL Database/Remove-FabricSQLDatabase.ps1 index 067df9a9..e6dc06bc 100644 --- a/source/Public/SQL Database/Remove-FabricSQLDatabase.ps1 +++ b/src/Public/SQL Database/Remove-FabricSQLDatabase.ps1 @@ -38,16 +38,16 @@ function Remove-FabricSQLDatabase try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "workspaces/{0}/sqldatabases/{1}" -f $WorkspaceId, $SQLDatabaseId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Delete SQL Database")) { - # Step 3: Make the API request + # Make the API request $apiParams = @{ Uri = $apiEndpointUrl Method = 'DELETE' @@ -62,7 +62,7 @@ function Remove-FabricSQLDatabase } catch { - # Step 5: Log and handle errors + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete SQL Database '$SQLDatabaseId' from workspace '$WorkspaceId'. Error: $errorDetails" -Level Error } diff --git a/src/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 b/src/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 new file mode 100644 index 00000000..d0ac4fc3 --- /dev/null +++ b/src/Public/SQL Endpoints/Get-FabricSQLEndpoint.ps1 @@ -0,0 +1,96 @@ +function Get-FabricSQLEndpoint { + <# + .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 + ```powershell + Get-FabricSQLEndpoint -WorkspaceId "workspace123" -SQLEndpointId "endpoint456" + ``` + + .EXAMPLE + ```powershell + Get-FabricSQLEndpoint -WorkspaceId "workspace123" -SQLEndpointName "MySQLEndpoint" + ``` + + .NOTES + Author: Tiago Balabuch, Kamil Nowinski +#> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$SQLEndpointId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SQLEndpointName + ) + + try { + # Handle ambiguous input + if ($SQLEndpointId -and $SQLEndpointName) { + Write-Message -Message "Both 'SQLEndpointId' and 'SQLEndpointName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/SQLEndpoints" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve SQL Endpoints + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $SQLEndpoints = @(Invoke-FabricRestMethod @apiParams) + + # 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 SQL Endpoints." -Level Debug + $SQLEndpoints + } + + # Handle results + if ($SQLEndpoint) { + Write-Message -Message "SQL Endpoint found matching the specified criteria." -Level Debug + return $SQLEndpoint + } else { + Write-Message -Message "No SQL Endpoint found matching the provided criteria." -Level Warning + return $null + } + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Paginated Report. Error: $errorDetails" -Level Error + } +} diff --git a/src/Public/Semantic Model/Get-FabricSemanticModel.ps1 b/src/Public/Semantic Model/Get-FabricSemanticModel.ps1 new file mode 100644 index 00000000..906d21ce --- /dev/null +++ b/src/Public/Semantic Model/Get-FabricSemanticModel.ps1 @@ -0,0 +1,98 @@ +function Get-FabricSemanticModel { + <# + .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 + This example retrieves the SemanticModel details for the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" + ``` + + .EXAMPLE + This example retrieves the SemanticModel details for the SemanticModel named "My SemanticModel" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelName "My SemanticModel" + ``` + + .NOTES + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$SemanticModelId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelName + ) + try { + # Handle ambiguous input + if ($SemanticModelId -and $SemanticModelName) { + Write-Message -Message "Both 'SemanticModelId' and 'SemanticModelName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/semanticModels" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve SemanticModels + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $SemanticModels = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SemanticModel. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 b/src/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 new file mode 100644 index 00000000..b91b4f77 --- /dev/null +++ b/src/Public/Semantic Model/Get-FabricSemanticModelDefinition.ps1 @@ -0,0 +1,78 @@ +function Get-FabricSemanticModelDefinition { + <# + .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 + This example retrieves the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" + ``` + + .EXAMPLE + This example retrieves the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345" in JSON format. + + ```powershell + Get-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" -SemanticModelFormat "json" + ``` + + .NOTES + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$SemanticModelId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('TMDL', 'TMSL')] + [string]$SemanticModelFormat = "TMDL" + ) + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/semanticModels/$SemanticModelId/getDefinition" + if ($SemanticModelFormat) { + $apiEndpointUrl = "$apiEndpointUrl?format=$SemanticModelFormat" + } + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve SemanticModel definition + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + + # Return the response + return $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SemanticModel. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Semantic Model/New-FabricSemanticModel.ps1 b/src/Public/Semantic Model/New-FabricSemanticModel.ps1 new file mode 100644 index 00000000..8ddf762e --- /dev/null +++ b/src/Public/Semantic Model/New-FabricSemanticModel.ps1 @@ -0,0 +1,102 @@ +function New-FabricSemanticModel +{ + <# + .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 + This example creates a new SemanticModel named "New SemanticModel" in the workspace with ID "workspace-12345" with the provided description. + + ```powershell + New-FabricSemanticModel -WorkspaceId "workspace-12345" -SemanticModelName "New SemanticModel" -SemanticModelDescription "Description of the new SemanticModel" + ``` + + .NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelDescription, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelPathDefinition + ) + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/semanticModels" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # 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 + + if ($PSCmdlet.ShouldProcess("Create SemanticModel", "Creating the SemanticModel '$SemanticModelName' in workspace '$WorkspaceId'.")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "SemanticModel '$SemanticModelName' created successfully!" -Level Info + return $response + } + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create SemanticModel. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Semantic Model/Remove-FabricSemanticModel.ps1 b/src/Public/Semantic Model/Remove-FabricSemanticModel.ps1 similarity index 55% rename from source/Public/Semantic Model/Remove-FabricSemanticModel.ps1 rename to src/Public/Semantic Model/Remove-FabricSemanticModel.ps1 index fe09a5c3..23e85ce8 100644 --- a/source/Public/Semantic Model/Remove-FabricSemanticModel.ps1 +++ b/src/Public/Semantic Model/Remove-FabricSemanticModel.ps1 @@ -22,10 +22,9 @@ function Remove-FabricSemanticModel ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -39,36 +38,27 @@ function Remove-FabricSemanticModel ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/semanticModels/$SemanticModelId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove SemanticModel")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove SemanticModel")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "SemanticModel '$SemanticModelId' deleted successfully from workspace '$WorkspaceId'." -Level Info } - - # 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 + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete SemanticModel '$SemanticModelId'. Error: $errorDetails" -Level Error } diff --git a/source/Public/Semantic Model/Update-FabricSemanticModel.ps1 b/src/Public/Semantic Model/Update-FabricSemanticModel.ps1 similarity index 65% rename from source/Public/Semantic Model/Update-FabricSemanticModel.ps1 rename to src/Public/Semantic Model/Update-FabricSemanticModel.ps1 index cee395b1..b5b9cf6f 100644 --- a/source/Public/Semantic Model/Update-FabricSemanticModel.ps1 +++ b/src/Public/Semantic Model/Update-FabricSemanticModel.ps1 @@ -28,10 +28,9 @@ function Update-FabricSemanticModel ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -53,14 +52,14 @@ function Update-FabricSemanticModel ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/semanticModels/$SemanticModelId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $SemanticModelName } @@ -74,32 +73,22 @@ function Update-FabricSemanticModel $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess("Update SemanticModel", "Updating the SemanticModel with ID '$SemanticModelId' in workspace '$WorkspaceId'.")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + if ($PSCmdlet.ShouldProcess("Update SemanticModel", "Updating the SemanticModel with ID '$SemanticModelId' in workspace '$WorkspaceId'.")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "SemanticModel '$SemanticModelName' updated successfully!" -Level Info + return $response } - - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update SemanticModel. Error: $errorDetails" -Level Error } diff --git a/src/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 b/src/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 new file mode 100644 index 00000000..9fbe3333 --- /dev/null +++ b/src/Public/Semantic Model/Update-FabricSemanticModelDefinition.ps1 @@ -0,0 +1,94 @@ +function Update-FabricSemanticModelDefinition +{ + <# + .SYNOPSIS + Updates the definition of an existing SemanticModel in a specified Microsoft Fabric workspace. + + .DESCRIPTION + This function sends a POST 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 + This example updates the definition of the SemanticModel with ID "SemanticModel-67890" in the workspace with ID "workspace-12345" using the provided definition file. + + ```powershell + Update-FabricSemanticModelDefinition -WorkspaceId "workspace-12345" -SemanticModelId "SemanticModel-67890" -SemanticModelPathDefinition "C:\Path\To\SemanticModelDefinition.json" + ``` + + .NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$SemanticModelId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$SemanticModelPathDefinition + ) + + # Ensure token validity + Confirm-TokenState + + $body = @{ + definition = @{ + parts = @() + } + } + + $jsonObjectParts = Get-FileDefinitionParts -sourceDirectory $SemanticModelPathDefinition + $body.definition.parts = $jsonObjectParts.parts + + $hasPlatformFile = $false + foreach ($part in $jsonObjectParts.parts) + { + if ($part.path -eq ".platform") + { + $hasPlatformFile = $true + Write-Message -Message "Platform File: $hasPlatformFile" -Level Debug + } + } + + $uri = "workspaces/$WorkspaceId/SemanticModels/$SemanticModelId/updateDefinition" + if ($hasPlatformFile) + { + $uri = "$uri?updateMetadata=true" + } + Write-Message -Message "API Endpoint: $uri" -Level Debug + + $bodyJson = $body | ConvertTo-Json -Depth 10 + Write-Message -Message "Request Body: $bodyJson" -Level Debug + + if ($PSCmdlet.ShouldProcess($SemanticModelId, "Update SemanticModel Definition")) + { + $apiParams = @{ + Uri = $uri + Method = 'Post' + Body = $bodyJson + TypeName = 'SemanticModel' + ObjectIdOrName = $SemanticModelId + HandleResponse = $true + } + + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Update definition for SemanticModel '$SemanticModelId' completed successfully!" -Level Info + $response + } +} diff --git a/src/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 b/src/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 new file mode 100644 index 00000000..7e0d24c5 --- /dev/null +++ b/src/Public/Spark Job Definition/Get-FabricSparkJobDefinition.ps1 @@ -0,0 +1,98 @@ +function Get-FabricSparkJobDefinition { + <# + .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 + This example retrieves the SparkJobDefinition details for the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" + ``` + + .EXAMPLE + This example retrieves the SparkJobDefinition details for the SparkJobDefinition named "My SparkJobDefinition" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricSparkJobDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionName "My SparkJobDefinition" + ``` + + .NOTES + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$SparkJobDefinitionId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$SparkJobDefinitionName + ) + try { + # Handle ambiguous input + if ($SparkJobDefinitionId -and $SparkJobDefinitionName) { + Write-Message -Message "Both 'SparkJobDefinitionId' and 'SparkJobDefinitionName' were provided. Please specify only one." -Level Error + return $null + } + + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/sparkJobDefinitions" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve Spark Job Definitions + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true + } + $SparkJobDefinitions = @(Invoke-FabricRestMethod @apiParams) + + # 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 + } + + # 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 { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SparkJobDefinition. Error: $errorDetails" -Level Error + } + +} diff --git a/src/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 b/src/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 new file mode 100644 index 00000000..8550a235 --- /dev/null +++ b/src/Public/Spark Job Definition/Get-FabricSparkJobDefinitionDefinition.ps1 @@ -0,0 +1,78 @@ +function Get-FabricSparkJobDefinitionDefinition { + <# + .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 + This example retrieves the definition of the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345". + + ```powershell + Get-FabricSparkJobDefinitionDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" + ``` + + .EXAMPLE + This example retrieves the definition of the SparkJobDefinition with ID "SparkJobDefinition-67890" in the workspace with ID "workspace-12345" in JSON format. + + ```powershell + Get-FabricSparkJobDefinitionDefinition -WorkspaceId "workspace-12345" -SparkJobDefinitionId "SparkJobDefinition-67890" -SparkJobDefinitionFormat "json" + ``` + + .NOTES + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$SparkJobDefinitionId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('SparkJobDefinitionV1', 'SparkJobDefinitionV2')] + [string]$SparkJobDefinitionFormat = "SparkJobDefinitionV1" + ) + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/sparkJobDefinitions/$SparkJobDefinitionId/getDefinition" + if ($SparkJobDefinitionFormat) { + $apiEndpointUrl += "?format=$SparkJobDefinitionFormat" + } + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + # Invoke the Fabric API to retrieve Spark Job Definition definition + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + + # Return the response + return $response + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve Spark Job Definition. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 b/src/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 similarity index 59% rename from source/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 rename to src/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 index 234751c5..2bec09c6 100644 --- a/source/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 +++ b/src/Public/Spark Job Definition/New-FabricSparkJobDefinition.ps1 @@ -31,10 +31,9 @@ function New-FabricSparkJobDefinition ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -60,14 +59,14 @@ function New-FabricSparkJobDefinition ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/sparkJobDefinitions" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/sparkJobDefinitions" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $SparkJobDefinitionName } @@ -138,70 +137,22 @@ function New-FabricSparkJobDefinition $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create Spark Job Definition")) - { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - 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." + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create Spark Job Definition")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionName' created successfully!" -Level Info + return $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create Spark Job Definition. Error: $errorDetails" -Level Error } diff --git a/source/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 b/src/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 similarity index 56% rename from source/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 rename to src/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 index daefb4d6..853b3990 100644 --- a/source/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 +++ b/src/Public/Spark Job Definition/Remove-FabricSparkJobDefinition.ps1 @@ -22,10 +22,9 @@ function Remove-FabricSparkJobDefinition ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -39,34 +38,27 @@ function Remove-FabricSparkJobDefinition ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove SparkJobDefinition")) - { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } - # 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 - } + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/sparkJobDefinitions/$SparkJobDefinitionId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - Write-Message -Message "Spark Job Definition '$SparkJobDefinitionId' deleted successfully from workspace '$WorkspaceId'." -Level Info + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove SparkJobDefinition")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionId' deleted successfully from workspace '$WorkspaceId'." -Level Info + } } catch { - # Step 5: Log and handle errors + # Log and handle errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to delete SparkJobDefinition '$SparkJobDefinitionId'. Error: $errorDetails" -Level Error } diff --git a/src/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 b/src/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 new file mode 100644 index 00000000..d6fb6e30 --- /dev/null +++ b/src/Public/Spark Job Definition/Start-FabricSparkJobDefinitionOnDemand.ps1 @@ -0,0 +1,82 @@ +function Start-FabricSparkJobDefinitionOnDemand +{ + <# + .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 + ```powershell + 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. + + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$SparkJobDefinitionId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [ValidateSet('sparkjob')] + [string]$JobType = "sparkjob", + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [bool]$waitForCompletion = $false + ) + + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/SparkJobDefinitions/$SparkJobDefinitionId/jobs/instances?jobType=$JobType" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug + + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Start Spark Job Definition on demand")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + NoWait = (-not $waitForCompletion) + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Spark Job Definition on demand successfully initiated for SparkJobDefinition." -Level Info + return $response + } + } + catch { + # 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/source/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 b/src/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 similarity index 65% rename from source/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 rename to src/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 index 50dcf33e..48f0ef1d 100644 --- a/source/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 +++ b/src/Public/Spark Job Definition/Update-FabricSparkJobDefinition.ps1 @@ -28,10 +28,9 @@ function Update-FabricSparkJobDefinition ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -53,14 +52,14 @@ function Update-FabricSparkJobDefinition ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/sparkJobDefinitions/$SparkJobDefinitionId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $SparkJobDefinitionName } @@ -74,32 +73,22 @@ function Update-FabricSparkJobDefinition $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update SparkJobDefinition")) - { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update SparkJobDefinition")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Spark Job Definition '$SparkJobDefinitionName' updated successfully!" -Level Info + return $response } - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update SparkJobDefinition. Error: $errorDetails" -Level Error } diff --git a/source/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 b/src/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 similarity index 55% rename from source/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 rename to src/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 index e9eb3554..1ec6b0b5 100644 --- a/source/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 +++ b/src/Public/Spark Job Definition/Update-FabricSparkJobDefinitionDefinition.ps1 @@ -28,10 +28,9 @@ function Update-FabricSparkJobDefinitionDefinition ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -53,20 +52,17 @@ function Update-FabricSparkJobDefinitionDefinition ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/SparkJobDefinitions/$SparkJobDefinitionId/updateDefinition" + if ($SparkJobDefinitionPathPlatformDefinition) { + $apiEndpointUrl = "$apiEndpointUrl?updateMetadata=true" } - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ definition = @{ format = "SparkJobDefinitionV1" @@ -116,68 +112,22 @@ function Update-FabricSparkJobDefinitionDefinition $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Spark Job Definition")) - { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Spark Job Definition")) { + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Update definition for Spark Job Definition '$SparkJobDefinitionId' created successfully!" -Level Info + return $response } } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Spark Job Definition. Error: $errorDetails" -Level Error } diff --git a/source/Public/Spark/Get-FabricSparkCustomPool.ps1 b/src/Public/Spark/Get-FabricSparkCustomPool.ps1 similarity index 50% rename from source/Public/Spark/Get-FabricSparkCustomPool.ps1 rename to src/Public/Spark/Get-FabricSparkCustomPool.ps1 index 32c5d3c3..7fb51848 100644 --- a/source/Public/Spark/Get-FabricSparkCustomPool.ps1 +++ b/src/Public/Spark/Get-FabricSparkCustomPool.ps1 @@ -39,11 +39,8 @@ function Get-FabricSparkCustomPool { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` 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 + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -61,74 +58,28 @@ function Get-FabricSparkCustomPool { ) try { - # Step 1: Handle ambiguous input + # 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 + # Ensure token validity Confirm-TokenState - # Step 3: Initialize variables - $continuationToken = $null - $SparkCustomPools = @() - if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { - Add-Type -AssemblyName System.Web + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/spark/pools" -f $WorkspaceId + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + HandleResponse = $true + ExtractValue = 'True' + TypeName = 'SparkCustomPool' } + $SparkCustomPools = @(Invoke-FabricRestMethod @apiParams) - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 + # Filter results based on provided parameters $SparkCustomPool = if ($SparkCustomPoolId) { $SparkCustomPools | Where-Object { $_.id -eq $SparkCustomPoolId } } elseif ($SparkCustomPoolName) { @@ -139,7 +90,7 @@ function Get-FabricSparkCustomPool { $SparkCustomPools } - # Step 9: Handle results + # Handle results if ($SparkCustomPool) { Write-Message -Message "SparkCustomPool found matching the specified criteria." -Level Debug return $SparkCustomPool @@ -148,7 +99,7 @@ function Get-FabricSparkCustomPool { return $null } } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve SparkCustomPool. Error: $errorDetails" -Level Error } diff --git a/src/Public/Spark/Get-FabricSparkSettings.ps1 b/src/Public/Spark/Get-FabricSparkSettings.ps1 new file mode 100644 index 00000000..0a9e191b --- /dev/null +++ b/src/Public/Spark/Get-FabricSparkSettings.ps1 @@ -0,0 +1,63 @@ +function Get-FabricSparkSettings { + <# + .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 + This example retrieves the Spark settings for the workspace with ID "workspace-12345". + + ```powershell + Get-FabricSparkSettings -WorkspaceId "workspace-12345" + ``` + + .NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding()] + [OutputType([System.Object[]])] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$WorkspaceId + ) + + try { + + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/spark/settings" -f $WorkspaceId + + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + HandleResponse = $true + TypeName = 'SparkSettings' + } + $SparkSettings = Invoke-FabricRestMethod @apiParams + + # Handle results + if ($SparkSettings) { + Write-Message -Message "Returning all Spark Settings." -Level Debug + return $SparkSettings + } else { + Write-Message -Message "No SparkSettings found matching the provided criteria." -Level Warning + return $null + } + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve SparkSettings. Error: $errorDetails" -Level Error + } + +} diff --git a/source/Public/Spark/New-FabricSparkCustomPool.ps1 b/src/Public/Spark/New-FabricSparkCustomPool.ps1 similarity index 60% rename from source/Public/Spark/New-FabricSparkCustomPool.ps1 rename to src/Public/Spark/New-FabricSparkCustomPool.ps1 index 3c801cb7..2437f13a 100644 --- a/source/Public/Spark/New-FabricSparkCustomPool.ps1 +++ b/src/Public/Spark/New-FabricSparkCustomPool.ps1 @@ -46,10 +46,9 @@ function New-FabricSparkCustomPool ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -98,14 +97,13 @@ function New-FabricSparkCustomPool try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/spark/pools" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/spark/pools" -f $WorkspaceId - # Step 3: Construct the request body + # Construct the request body $body = @{ name = $SparkCustomPoolName nodeFamily = $NodeFamily @@ -127,67 +125,22 @@ function New-FabricSparkCustomPool if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create Spark Custom Pool")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - } - - # 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." + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + TypeName = 'SparkCustomPool' + ObjectIdOrName = $SparkCustomPoolName } + $response = Invoke-FabricRestMethod @apiParams } + + return $response } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create SparkCustomPool. Error: $errorDetails" -Level Error } diff --git a/source/Public/Spark/Remove-FabricSparkCustomPool.ps1 b/src/Public/Spark/Remove-FabricSparkCustomPool.ps1 similarity index 92% rename from source/Public/Spark/Remove-FabricSparkCustomPool.ps1 rename to src/Public/Spark/Remove-FabricSparkCustomPool.ps1 index 41414784..6de61072 100644 --- a/source/Public/Spark/Remove-FabricSparkCustomPool.ps1 +++ b/src/Public/Spark/Remove-FabricSparkCustomPool.ps1 @@ -39,22 +39,22 @@ function Remove-FabricSparkCustomPool ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/spark/pools/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkCustomPoolId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Remove Spark Custom Pool")) { - # Step 3: Make the API request + # Make the API request $response = Invoke-FabricRestMethod ` -Uri $apiEndpointUrl ` -Method Delete } - # Step 4: Validate the response code + # Validate the response code if ($statusCode -ne 200) { Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Error @@ -68,7 +68,7 @@ function Remove-FabricSparkCustomPool } catch { - # Step 5: Log and handle errors + # 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/source/Public/Spark/Update-FabricSparkCustomPool.ps1 b/src/Public/Spark/Update-FabricSparkCustomPool.ps1 similarity index 81% rename from source/Public/Spark/Update-FabricSparkCustomPool.ps1 rename to src/Public/Spark/Update-FabricSparkCustomPool.ps1 index 3181fece..759737a4 100644 --- a/source/Public/Spark/Update-FabricSparkCustomPool.ps1 +++ b/src/Public/Spark/Update-FabricSparkCustomPool.ps1 @@ -49,10 +49,9 @@ function Update-FabricSparkCustomPool ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -105,14 +104,14 @@ function Update-FabricSparkCustomPool try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/spark/pools/{2}" -f $FabricConfig.BaseUrl, $WorkspaceId, $SparkCustomPoolId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/spark/pools/{1}" -f $WorkspaceId, $SparkCustomPoolId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ name = $InstancePoolName nodeFamily = $NodeFamily @@ -135,31 +134,22 @@ function Update-FabricSparkCustomPool if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update SparkCustomPool")) { - - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson - } - - # 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 + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + TypeName = 'SparkCustomPool' + ObjectIdOrName = $SparkCustomPoolId + } + $response = Invoke-FabricRestMethod @apiParams } - # Step 6: Handle results - Write-Message -Message "Spark Custom Pool '$SparkCustomPoolName' updated successfully!" -Level Info return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update SparkCustomPool. Error: $errorDetails" -Level Error } diff --git a/src/Public/Spark/Update-FabricSparkSettings.ps1 b/src/Public/Spark/Update-FabricSparkSettings.ps1 new file mode 100644 index 00000000..ab6331a1 --- /dev/null +++ b/src/Public/Spark/Update-FabricSparkSettings.ps1 @@ -0,0 +1,195 @@ +function Update-FabricSparkSettings +{ + <# + .SYNOPSIS + Updates Spark settings in a specified Microsoft Fabric workspace. + + .DESCRIPTION + This function sends a PATCH request to the Microsoft Fabric API to update Spark settings + in the specified workspace. It supports optional parameters for automatic logging, high concurrency, + pool configuration, environment, and starter pool settings. + + .PARAMETER WorkspaceId + The unique identifier of the workspace whose Spark settings will be updated. This parameter is mandatory. + + .PARAMETER automaticLogEnabled + Specifies whether automatic logging is enabled. This parameter is optional. + + .PARAMETER notebookInteractiveRunEnabled + Specifies whether notebook interactive run (high concurrency) is enabled. This parameter is optional. + + .PARAMETER customizeComputeEnabled + Specifies whether compute customization is enabled for the pool. This parameter is optional. + + .PARAMETER defaultPoolName + The name of the default pool. Must be provided together with defaultPoolType. This parameter is optional. + + .PARAMETER defaultPoolType + The type of the default pool. Must be 'Workspace' or 'Capacity'. Must be provided together with defaultPoolName. This parameter is optional. + + .PARAMETER starterPoolMaxNode + The maximum number of nodes for the starter pool. This parameter is optional. + + .PARAMETER starterPoolMaxExecutors + The maximum number of executors for the starter pool. This parameter is optional. + + .PARAMETER EnvironmentName + The name of the environment. This parameter is optional. + + .PARAMETER EnvironmentRuntimeVersion + The runtime version of the environment. This parameter is optional. + + .EXAMPLE + This example enables automatic logging for the workspace with ID "workspace-12345". + + ```powershell + Update-FabricSparkSettings -WorkspaceId "workspace-12345" -automaticLogEnabled $true + ``` + + .EXAMPLE + This example sets the default pool for the workspace with ID "workspace-12345". + + ```powershell + Update-FabricSparkSettings -WorkspaceId "workspace-12345" -defaultPoolName "MyPool" -defaultPoolType "Workspace" + ``` + + .NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + + #> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [guid]$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 + { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/spark/settings" -f $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Construct the request body + $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 + + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update SparkSettings")) + { + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + TypeName = 'SparkSettings' + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Spark Settings updated successfully!" -Level Info + } + + return $response + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to update SparkSettings. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Tenant/Get-FabricCapacityTenantSettingOverrides.ps1 b/src/Public/Tenant/Get-FabricCapacityTenantSettingOverrides.ps1 similarity index 61% rename from source/Public/Tenant/Get-FabricCapacityTenantSettingOverrides.ps1 rename to src/Public/Tenant/Get-FabricCapacityTenantSettingOverrides.ps1 index b74f0470..cd0a7ccf 100644 --- a/source/Public/Tenant/Get-FabricCapacityTenantSettingOverrides.ps1 +++ b/src/Public/Tenant/Get-FabricCapacityTenantSettingOverrides.ps1 @@ -24,10 +24,9 @@ function Get-FabricCapacityTenantSettingOverrides { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -37,34 +36,36 @@ function Get-FabricCapacityTenantSettingOverrides { ) try { - # Step 1: Validate authentication token before making API requests + # Validate authentication token before making API requests Confirm-TokenState - # Step 2: Construct the API endpoint URL for retrieving capacity tenant setting overrides - if ($capacityId) { - $apiEndpointURI = "admin/capacities/{0}/delegatedTenantSettingOverrides" -f $capacityId - $message = "Successfully retrieved tenant setting overrides for capacity ID: $capacityId." + # Construct the API endpoint URL for retrieving capacity tenant setting overrides + if ($CapacityId) { + $apiEndpointUrl = "admin/capacities/{0}/delegatedTenantSettingOverrides" -f $CapacityId } else { - $apiEndpointURI = "admin/capacities/delegatedTenantSettingOverrides" -f $FabricConfig.BaseUrl - $message = "Successfully retrieved capacity tenant setting overrides." + $apiEndpointUrl = "admin/capacities/delegatedTenantSettingOverrides" } - Write-Message -Message "Constructed API Endpoint: $apiEndpointURI" -Level Debug + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Invoke the Fabric API to retrieve capacity tenant setting overrides - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Get + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + HandleResponse = $true + ExtractValue = 'True' + TypeName = 'CapacityTenantSettingOverride' + } + $response = Invoke-FabricRestMethod @apiParams - # Step 4: Check if any capacity tenant setting overrides were retrieved and handle results accordingly + # Check if any capacity tenant setting overrides were retrieved and handle results accordingly if ($response) { - Write-Message -Message $message -Level Debug + Write-Message -Message "Successfully retrieved capacity tenant setting overrides." -Level Debug return $response } else { Write-Message -Message "No capacity tenant setting overrides found." -Level Warning return $null } } catch { - # Step 5: Log detailed error information if the API request fails + # Log detailed error information if the API request fails $errorDetails = $_.Exception.Message Write-Message -Message "Error retrieving capacity tenant setting overrides: $errorDetails" -Level Error } diff --git a/source/Public/Tenant/Get-FabricDomainTenantSettingOverrides.ps1 b/src/Public/Tenant/Get-FabricDomainTenantSettingOverrides.ps1 similarity index 62% rename from source/Public/Tenant/Get-FabricDomainTenantSettingOverrides.ps1 rename to src/Public/Tenant/Get-FabricDomainTenantSettingOverrides.ps1 index b0f67566..0b713717 100644 --- a/source/Public/Tenant/Get-FabricDomainTenantSettingOverrides.ps1 +++ b/src/Public/Tenant/Get-FabricDomainTenantSettingOverrides.ps1 @@ -14,29 +14,31 @@ function Get-FabricDomainTenantSettingOverrides { ``` .NOTES - - Requires the `$FabricConfig` global configuration, which must include `BaseUrl` and `FabricHeaders`. - Ensures token validity by invoking `Confirm-TokenState` before making the API request. - - Logs detailed messages for debugging and error handling. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( ) try { - # Step 1: Validate authentication token before making API requests + # Validate authentication token before making API requests Confirm-TokenState - # Step 2: Construct the API endpoint URL for retrieving domain tenant setting overrides - $apiEndpointURI = "admin/domains/delegatedTenantSettingOverrides" - Write-Message -Message "Constructed API Endpoint: $apiEndpointURI" -Level Debug + # Construct the API endpoint URL for retrieving domain tenant setting overrides + $apiEndpointUrl = "admin/domains/delegatedTenantSettingOverrides" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Invoke the Fabric API to retrieve domain tenant setting overrides - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Get + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + HandleResponse = $true + ExtractValue = 'True' + TypeName = 'DomainTenantSettingOverride' + } + $response = Invoke-FabricRestMethod @apiParams - # Step 4: Check if any domain tenant setting overrides were retrieved and handle results accordingly + # Check if any domain tenant setting overrides were retrieved and handle results accordingly if ($response) { Write-Message -Message "Successfully retrieved domain tenant setting overrides." -Level Debug return $response @@ -45,7 +47,7 @@ function Get-FabricDomainTenantSettingOverrides { return $null } } catch { - # Step 5: Log detailed error information if the API request fails + # Log detailed error information if the API request fails $errorDetails = $_.Exception.Message Write-Message -Message "Error retrieving domain tenant setting overrides: $errorDetails" -Level Error } diff --git a/source/Public/Tenant/Get-FabricTenantSetting.ps1 b/src/Public/Tenant/Get-FabricTenantSetting.ps1 similarity index 55% rename from source/Public/Tenant/Get-FabricTenantSetting.ps1 rename to src/Public/Tenant/Get-FabricTenantSetting.ps1 index d37737ee..fc9b5846 100644 --- a/source/Public/Tenant/Get-FabricTenantSetting.ps1 +++ b/src/Public/Tenant/Get-FabricTenantSetting.ps1 @@ -24,10 +24,7 @@ function Get-FabricTenantSetting { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Is-TokenExpired` to ensure token validity before making the API request. - - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -37,39 +34,41 @@ function Get-FabricTenantSetting { ) try { - # Step 1: Validate authentication token before making API requests + # Validate authentication token before making API requests Write-Message -Message "Validating authentication token..." -Level Debug Confirm-TokenState Write-Message -Message "Authentication token is valid." -Level Debug - # Step 2: Construct the API endpoint URL for retrieving tenant settings - $apiEndpointURI = "admin/tenantsettings" - Write-Message -Message "Constructed API Endpoint: $apiEndpointURI" -Level Debug + # Construct the API endpoint URL for retrieving tenant settings + $apiEndpointUrl = "admin/tenantsettings" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Invoke the Fabric API to retrieve tenant settings - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Get + # Invoke the Fabric API to retrieve tenant settings + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'Auto' + HandleResponse = $true + } + $settings = Invoke-FabricRestMethod @apiParams - # Step 4: Filter tenant settings based on the provided SettingTitle parameter (if specified) - $settings = if ($SettingTitle) { + # Filter tenant settings based on the provided SettingTitle parameter (if specified) + if ($SettingTitle) { Write-Message -Message "Filtering tenant settings by title: '$SettingTitle'" -Level Debug - $response.tenantSettings | Where-Object { $_.title -eq $SettingTitle } + $filteredSettings = $settings | Where-Object { $_.title -eq $SettingTitle } + if ($filteredSettings) { + Write-Message -Message "Tenant settings successfully retrieved." -Level Debug + return $filteredSettings + } else { + Write-Message -Message "No tenant settings found matching the specified criteria." -Level Warning + return $null + } } else { Write-Message -Message "No filter specified. Retrieving all tenant settings." -Level Debug - $response.tenantSettings - } - - # Step 5: Check if any tenant settings were found and return results accordingly - if ($settings) { - Write-Message -Message "Tenant settings successfully retrieved." -Level Debug return $settings - } else { - Write-Message -Message "No tenant settings found matching the specified criteria." -Level Warning - return $null } } catch { - # Step 6: Log detailed error information if the API request fails + # Log detailed error information if the API request fails $errorDetails = $_.Exception.Message Write-Message -Message "Error retrieving tenant settings: $errorDetails" -Level Error } diff --git a/src/Public/Tenant/Get-FabricWorkspaceTenantSettingOverrides.ps1 b/src/Public/Tenant/Get-FabricWorkspaceTenantSettingOverrides.ps1 new file mode 100644 index 00000000..bbe38fd1 --- /dev/null +++ b/src/Public/Tenant/Get-FabricWorkspaceTenantSettingOverrides.ps1 @@ -0,0 +1,45 @@ +function Get-FabricWorkspaceTenantSettingOverrides { + <# + .SYNOPSIS + Retrieves tenant setting overrides for all workspaces in the Fabric tenant. + + .DESCRIPTION + The `Get-FabricWorkspaceTenantSettingOverrides` function retrieves tenant setting overrides for all workspaces in the Fabric tenant by making a GET request to the appropriate API endpoint. The function validates the authentication token before making the request and handles the response accordingly. + + .EXAMPLE + Returns all workspaces tenant setting overrides. + + ```powershell + Get-FabricWorkspaceTenantSettingOverrides + ``` + + .NOTES + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding()] + param ( ) + + try { + # Validate authentication token before making API requests + Confirm-TokenState + + # Construct the API endpoint URL for retrieving workspaces tenant setting overrides + $apiEndpointUrl = "admin/workspaces/delegatedTenantSettingOverrides" + + # Invoke the Fabric API to retrieve workspaces tenant setting overrides + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'Auto' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + + Write-Message -Message "Successfully retrieved workspaces tenant setting overrides." -Level Debug + return $response + } catch { + # Log detailed error information if the API request fails + $errorDetails = $_.Exception.Message + Write-Message -Message "Error retrieving workspaces tenant setting overrides: $errorDetails" -Level Error + } +} diff --git a/source/Public/Tenant/Revoke-FabricCapacityTenantSettingOverrides.ps1 b/src/Public/Tenant/Revoke-FabricCapacityTenantSettingOverrides.ps1 similarity index 63% rename from source/Public/Tenant/Revoke-FabricCapacityTenantSettingOverrides.ps1 rename to src/Public/Tenant/Revoke-FabricCapacityTenantSettingOverrides.ps1 index 0ed2ae46..2fff1f15 100644 --- a/source/Public/Tenant/Revoke-FabricCapacityTenantSettingOverrides.ps1 +++ b/src/Public/Tenant/Revoke-FabricCapacityTenantSettingOverrides.ps1 @@ -20,10 +20,7 @@ function Revoke-FabricCapacityTenantSettingOverrides { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -36,23 +33,26 @@ function Revoke-FabricCapacityTenantSettingOverrides { [string]$tenantSettingName ) try { - # Step 1: Validate authentication token before making API requests + # Validate authentication token before making API requests Confirm-TokenState - # Step 2: Construct the API endpoint URL for retrieving capacity tenant setting overrides - $apiEndpointURI = "admin/capacities/{0}/delegatedTenantSettingOverrides/{1}" -f $capacityId, $tenantSettingName - Write-Message -Message "Constructed API Endpoint: $apiEndpointURI" -Level Debug + # Construct the API endpoint URL for retrieving capacity tenant setting overrides + $apiEndpointUrl = "admin/capacities/{0}/delegatedTenantSettingOverrides/{1}" -f $capacityId, $tenantSettingName + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess("$tenantSettingName" , "Revoke")) { - # Step 3: Invoke the Fabric API to retrieve capacity tenant setting overrides - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Delete + # Invoke the Fabric API to remove capacity tenant setting override + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Successfully removed the tenant setting override '$tenantSettingName' from the capacity with ID '$capacityId'." -Level Info + return $response } - Write-Message -Message "Successfully removed the tenant setting override '$tenantSettingName' from the capacity with ID '$capacityId'." -Level Info - return $response } catch { - # Step 5: Log detailed error information if the API request fails + # Log detailed error information if the API request fails $errorDetails = $_.Exception.Message Write-Message -Message "Error retrieving capacity tenant setting overrides: $errorDetails" -Level Error } diff --git a/source/Public/Tenant/Update-FabricCapacityTenantSettingOverrides.ps1 b/src/Public/Tenant/Update-FabricCapacityTenantSettingOverrides.ps1 similarity index 86% rename from source/Public/Tenant/Update-FabricCapacityTenantSettingOverrides.ps1 rename to src/Public/Tenant/Update-FabricCapacityTenantSettingOverrides.ps1 index 7603f24b..16b671b4 100644 --- a/source/Public/Tenant/Update-FabricCapacityTenantSettingOverrides.ps1 +++ b/src/Public/Tenant/Update-FabricCapacityTenantSettingOverrides.ps1 @@ -40,10 +40,7 @@ function Update-FabricCapacityTenantSettingOverrides ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -101,7 +98,7 @@ function Update-FabricCapacityTenantSettingOverrides } # Construct API endpoint URL - $apiEndpointURI = "admin/capacities/{0}/delegatedTenantSettingOverrides" -f $CapacityId + $apiEndpointUrl = "admin/capacities/{0}/delegatedTenantSettingOverrides" -f $CapacityId # Construct request body $body = @{ @@ -127,16 +124,19 @@ function Update-FabricCapacityTenantSettingOverrides # Convert body to JSON $bodyJson = $body | ConvertTo-Json -Depth 4 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Update Tenant Setting Overrides")){ + + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Tenant Setting Overrides")) { # Invoke Fabric API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -method Post ` - -body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Successfully updated capacity tenant setting overrides for CapacityId: $CapacityId and SettingTitle: $SettingTitle." -Level Info + return $response } - - Write-Message -Message "Successfully updated capacity tenant setting overrides for CapacityId: $CapacityId and SettingTitle: $SettingTitle." -Level Info - return $response } catch { diff --git a/source/Public/Tenant/Update-FabricTenantSetting.ps1 b/src/Public/Tenant/Update-FabricTenantSetting.ps1 similarity index 89% rename from source/Public/Tenant/Update-FabricTenantSetting.ps1 rename to src/Public/Tenant/Update-FabricTenantSetting.ps1 index a3c84a05..5774f9b4 100644 --- a/source/Public/Tenant/Update-FabricTenantSetting.ps1 +++ b/src/Public/Tenant/Update-FabricTenantSetting.ps1 @@ -40,10 +40,7 @@ function Update-FabricCapacityTenantSettingOverrides ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - - Calls `Confirm-TokenState` to ensure token validity before making the API request. - - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -121,8 +118,8 @@ function Update-FabricCapacityTenantSettingOverrides } # Construct API endpoint URL - $apiEndpointURI = "admin/tenantsettings/{0}/update" -f $TenantSettingName - Write-Message -Message "Constructed API Endpoint: $apiEndpointURI" -Level Debug + $apiEndpointUrl = "admin/tenantsettings/{0}/update" -f $TenantSettingName + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug # Construct request body $body = @{ @@ -163,18 +160,18 @@ function Update-FabricCapacityTenantSettingOverrides $bodyJson = $body | ConvertTo-Json -Depth 5 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Update Tenant Setting")) - { - + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Tenant Setting")) { # Invoke Fabric API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -method Post ` - -body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Successfully updated tenant setting." -Level Info + return $response } - - Write-Message -Message "Successfully updated tenant setting." -Level Info - return $response } catch { diff --git a/source/Public/Users/Get-FabricUserListAccessEntities.ps1 b/src/Public/Users/Get-FabricUserListAccessEntities.ps1 similarity index 78% rename from source/Public/Users/Get-FabricUserListAccessEntities.ps1 rename to src/Public/Users/Get-FabricUserListAccessEntities.ps1 index 0f3a4499..bfea7904 100644 --- a/source/Public/Users/Get-FabricUserListAccessEntities.ps1 +++ b/src/Public/Users/Get-FabricUserListAccessEntities.ps1 @@ -28,10 +28,9 @@ function Get-FabricUserListAccessEntities { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -49,21 +48,25 @@ function Get-FabricUserListAccessEntities { Confirm-TokenState - # Step 4: Loop to retrieve all capacities with continuation token - $apiEndpointURI = "admin/users/{0}/access" -f $UserId + $apiEndpointUrl = "admin/users/{0}/access" -f $UserId if ($Type) { - $apiEndpointURI += "?type=$Type" + $apiEndpointUrl += "?type=$Type" } - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -Method Get + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + HandleResponse = $true + ExtractValue = 'True' + TypeName = 'UserAccessEntity' + } + $response = Invoke-FabricRestMethod @apiParams return $response } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message - Write-Message -Message "Failed to retrieve Warehouse. Error: $errorDetails" -Level Error + Write-Message -Message "Failed to retrieve user access entities. Error: $errorDetails" -Level Error } } diff --git a/source/Public/Utils/Convert-FromBase64.ps1 b/src/Public/Utils/Convert-FromBase64.ps1 similarity index 87% rename from source/Public/Utils/Convert-FromBase64.ps1 rename to src/Public/Utils/Convert-FromBase64.ps1 index b9dd134e..324a771d 100644 --- a/source/Public/Utils/Convert-FromBase64.ps1 +++ b/src/Public/Utils/Convert-FromBase64.ps1 @@ -40,16 +40,16 @@ Author: Tiago Balabuch ) try { - # Step 1: Convert the Base64 string to a byte array + # Convert the Base64 string to a byte array $bytes = [Convert]::FromBase64String($Base64String) - # Step 2: Convert the byte array back to a UTF-8 string + # Convert the byte array back to a UTF-8 string $decodedString = [System.Text.Encoding]::UTF8.GetString($bytes) - # Step 3: Return the decoded string + # Return the decoded string return $decodedString } catch { - # Step 4: Handle and log errors + # 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: $_" diff --git a/source/Public/Utils/Convert-ToBase64.ps1 b/src/Public/Utils/Convert-ToBase64.ps1 similarity index 91% rename from source/Public/Utils/Convert-ToBase64.ps1 rename to src/Public/Utils/Convert-ToBase64.ps1 index 48560bed..6815d76d 100644 --- a/source/Public/Utils/Convert-ToBase64.ps1 +++ b/src/Public/Utils/Convert-ToBase64.ps1 @@ -44,20 +44,20 @@ Author: Tiago Balabuch ) try { - # Step 1: Reading all the bytes from the file + # 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 + # 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 + # 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 + # 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: $_" diff --git a/source/Public/Utils/Get-FabricLongRunningOperation.ps1 b/src/Public/Utils/Get-FabricLongRunningOperation.ps1 similarity index 92% rename from source/Public/Utils/Get-FabricLongRunningOperation.ps1 rename to src/Public/Utils/Get-FabricLongRunningOperation.ps1 index 4a6bc07a..a47ecccb 100644 --- a/source/Public/Utils/Get-FabricLongRunningOperation.ps1 +++ b/src/Public/Utils/Get-FabricLongRunningOperation.ps1 @@ -42,7 +42,7 @@ Author: Tiago Balabuch Write-Message -Message "[Get-FabricLongRunningOperation]::Begin" -Level Debug Confirm-TokenState - # Step 1: Construct the API URL + # Construct the API URL if (-not $OperationId) { # Use the Location header to define the operationUrl, if OperationId is not provided $apiEndpointUrl = $Location @@ -62,7 +62,7 @@ Author: Tiago Balabuch try { do { - # Step 2: Wait before the next request + # Wait before the next request if ($RetryAfter) { Write-Message -Message "Waiting $RetryAfter seconds..." -Level Verbose Start-Sleep -Seconds $RetryAfter @@ -71,10 +71,10 @@ Author: Tiago Balabuch Start-Sleep -Seconds 5 # Default retry interval if no Retry-After header } - # Step 3: Make the API request + # Make the API request $response = Invoke-FabricRestMethod -Uri $apiEndpointUrl -Method Get - # Step 4: Parse the response + # Parse the response $jsonOperation = $response | ConvertTo-Json $operation = $jsonOperation | ConvertFrom-Json @@ -83,11 +83,11 @@ Author: Tiago Balabuch } while ($operation.status -notin @("Succeeded", "Completed", "Failed")) - # Step 5: Return the operation result + # Return the operation result return $operation } catch { - # Step 6: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "An error occurred while checking the operation: $errorDetails" -Level Error throw diff --git a/source/Public/Utils/Get-FabricLongRunningOperationResult.ps1 b/src/Public/Utils/Get-FabricLongRunningOperationResult.ps1 similarity index 92% rename from source/Public/Utils/Get-FabricLongRunningOperationResult.ps1 rename to src/Public/Utils/Get-FabricLongRunningOperationResult.ps1 index 54782e64..7169937b 100644 --- a/source/Public/Utils/Get-FabricLongRunningOperationResult.ps1 +++ b/src/Public/Utils/Get-FabricLongRunningOperationResult.ps1 @@ -31,15 +31,15 @@ Author: Tiago Balabuch Write-Message -Message "[Get-FabricLongRunningOperationResult]::Begin" -Level Debug Confirm-TokenState - # Step 1: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/operations/{1}/result" -f $FabricConfig.BaseUrl, $OperationId Write-Message -Message "[Get-FabricLongRunningOperationResult] API Endpoint: $apiEndpointUrl" -Level Debug try { - # Step 2: Make the API request + # Make the API request $response = Invoke-FabricRestMethod -Uri $apiEndpointUrl -Method Get - # Step 3: Validate the response code + # Validate the response code if ($script:statusCode -ne 200) { Write-Message -Message "Unexpected response code: $statusCode from the API." -Level Debug Write-Message -Message "Error: $($response.message)" -Level Debug @@ -50,7 +50,7 @@ Author: Tiago Balabuch return $response } catch { - # Step 3: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "An error occurred while returning the operation result: $errorDetails" -Level Error throw diff --git a/source/Public/Warehouse/Get-FabricWarehouse.ps1 b/src/Public/Warehouse/Get-FabricWarehouse.ps1 similarity index 81% rename from source/Public/Warehouse/Get-FabricWarehouse.ps1 rename to src/Public/Warehouse/Get-FabricWarehouse.ps1 index 95cad832..8d29548a 100644 --- a/source/Public/Warehouse/Get-FabricWarehouse.ps1 +++ b/src/Public/Warehouse/Get-FabricWarehouse.ps1 @@ -31,10 +31,9 @@ function Get-FabricWarehouse { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] param ( @@ -52,27 +51,30 @@ function Get-FabricWarehouse { ) try { - # Step 1: Handle ambiguous input + # 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 + # Ensure token validity Confirm-TokenState - # Step 3: Initialize variables + # Initialize variables - # Step 4: Loop to retrieve all capacities with continuation token - $apiEndpointURI = "workspaces/{0}/warehouses" -f $WorkspaceId + # Loop to retrieve all capacities with continuation token + $apiEndpointUrl = "workspaces/{0}/warehouses" -f $WorkspaceId $apiParams = @{ - Uri = $apiEndpointURI - Method = 'Get' + Uri = $apiEndpointUrl + Method = 'Get' + HandleResponse = $true + ExtractValue = 'True' + TypeName = 'Warehouse' } - $Warehouses = (Invoke-FabricRestMethod @apiParams).Value + $Warehouses = @(Invoke-FabricRestMethod @apiParams) - # Step 8: Filter results based on provided parameters + # Filter results based on provided parameters $Warehouse = if ($WarehouseId) { $Warehouses | Where-Object { $_.Id -eq $WarehouseId } } elseif ($WarehouseName) { @@ -83,7 +85,7 @@ function Get-FabricWarehouse { $Warehouses } - # Step 9: Handle results + # Handle results if ($Warehouse) { Write-Message -Message "Warehouse found matching the specified criteria." -Level Debug return $Warehouse @@ -92,7 +94,7 @@ function Get-FabricWarehouse { return $null } } catch { - # Step 10: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve Warehouse. Error: $errorDetails" -Level Error } diff --git a/source/Public/Warehouse/New-FabricWarehouse.ps1 b/src/Public/Warehouse/New-FabricWarehouse.ps1 similarity index 77% rename from source/Public/Warehouse/New-FabricWarehouse.ps1 rename to src/Public/Warehouse/New-FabricWarehouse.ps1 index 3857126b..dda8b437 100644 --- a/source/Public/Warehouse/New-FabricWarehouse.ps1 +++ b/src/Public/Warehouse/New-FabricWarehouse.ps1 @@ -25,10 +25,9 @@ function New-FabricWarehouse ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -47,14 +46,14 @@ function New-FabricWarehouse try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointURI = "workspaces/{0}/warehouses" -f $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointURI" -Level Debug + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/warehouses" -f $WorkspaceId + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $WarehouseName } @@ -67,13 +66,16 @@ function New-FabricWarehouse $bodyJson = $body | ConvertTo-Json -Depth 10 Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Create Warehouse")) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create Warehouse")) { - # Step 4: Make the API request + # Make the API request $apiParams = @{ - Uri = $apiEndpointURI - Method = 'Post' - Body = $bodyJson + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + TypeName = 'Warehouse' + ObjectIdOrName = $WarehouseName } $response = Invoke-FabricRestMethod @apiParams } @@ -84,7 +86,7 @@ function New-FabricWarehouse } catch { - # Step 6: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to create Warehouse. Error: $errorDetails" -Level Error } diff --git a/source/Public/Warehouse/Remove-FabricWarehouse.ps1 b/src/Public/Warehouse/Remove-FabricWarehouse.ps1 similarity index 73% rename from source/Public/Warehouse/Remove-FabricWarehouse.ps1 rename to src/Public/Warehouse/Remove-FabricWarehouse.ps1 index ce6f9a4b..8225d423 100644 --- a/source/Public/Warehouse/Remove-FabricWarehouse.ps1 +++ b/src/Public/Warehouse/Remove-FabricWarehouse.ps1 @@ -23,7 +23,7 @@ function Remove-FabricWarehouse .NOTES - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -37,32 +37,32 @@ function Remove-FabricWarehouse ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointURI = "workspaces/{0}/warehouses/{1}" -f $WorkspaceId, $WarehouseId + # Construct the API URL + $apiEndpointUrl = "workspaces/{0}/warehouses/{1}" -f $WorkspaceId, $WarehouseId - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Delete Warehouse")) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Delete Warehouse")) { - # Step 3: Make the API request and Validate the response - $apiParameters = @{ - Uri = $apiEndpointURI - Method = 'DELETE' + # Make the API request and Validate the response + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'DELETE' HandleResponse = $true - TypeName = "Warehouse" + TypeName = "Warehouse" ObjectIdOrName = $WarehouseId } - $response = Invoke-FabricRestMethod @apiParameters + $response = Invoke-FabricRestMethod @apiParams } - # Step 4: Handle results + # Handle results $response } catch { - # Step 5: Log and handle errors + # 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/source/Public/Warehouse/Update-FabricWarehouse.ps1 b/src/Public/Warehouse/Update-FabricWarehouse.ps1 similarity index 78% rename from source/Public/Warehouse/Update-FabricWarehouse.ps1 rename to src/Public/Warehouse/Update-FabricWarehouse.ps1 index 242e1b5c..2d8a6b38 100644 --- a/source/Public/Warehouse/Update-FabricWarehouse.ps1 +++ b/src/Public/Warehouse/Update-FabricWarehouse.ps1 @@ -28,10 +28,9 @@ function Update-FabricWarehouse ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] @@ -55,13 +54,14 @@ function Update-FabricWarehouse try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointURI = "workspaces/{0}/warehouses/{1}" -f $WorkspaceId, $WarehouseId + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/warehouses/$WarehouseId" + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $WarehouseName } @@ -75,21 +75,23 @@ function Update-FabricWarehouse $bodyJson = $body | ConvertTo-Json Write-Message -Message "Request Body: $bodyJson" -Level Debug - if ($PSCmdlet.ShouldProcess($apiEndpointURI, "Update Warehouse")) + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Warehouse")) { - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointURI ` - -method Patch ` - -body $bodyJson + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams } - # Step 6: Handle results Write-Message -Message "Warehouse '$WarehouseName' updated successfully!" -Level Info return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update Warehouse. Error: $errorDetails" -Level Error } diff --git a/source/Public/Workspace/Add-FabricWorkspaceCapacity.ps1 b/src/Public/Workspace/Add-FabricWorkspaceCapacity.ps1 similarity index 62% rename from source/Public/Workspace/Add-FabricWorkspaceCapacity.ps1 rename to src/Public/Workspace/Add-FabricWorkspaceCapacity.ps1 index 97183412..8acc05bd 100644 --- a/source/Public/Workspace/Add-FabricWorkspaceCapacity.ps1 +++ b/src/Public/Workspace/Add-FabricWorkspaceCapacity.ps1 @@ -20,10 +20,9 @@ function Add-FabricWorkspaceCapacity { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] [Alias("Assign-FabricWorkspaceCapacity")] @@ -39,14 +38,14 @@ function Add-FabricWorkspaceCapacity { ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/assignToCapacity" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/assignToCapacity" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ capacityId = $CapacityId } @@ -55,22 +54,17 @@ function Add-FabricWorkspaceCapacity { $bodyJson = $body | ConvertTo-Json -Depth 4 Write-Message -Message "Request Body: $bodyJson" -Level Debug - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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 + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams Write-Message -Message "Successfully assigned workspace with ID '$WorkspaceId' to capacity with ID '$CapacityId'." -Level Info } catch { - # Step 6: Capture and log error details + # 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/src/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 b/src/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 new file mode 100644 index 00000000..1e2ea7b9 --- /dev/null +++ b/src/Public/Workspace/Add-FabricWorkspaceIdentity.ps1 @@ -0,0 +1,55 @@ +function Add-FabricWorkspaceIdentity { + <# + .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 + Provisions a Managed Identity for the workspace with ID "workspace123". + + ```powershell + Add-FabricWorkspaceIdentity -WorkspaceId "workspace123" + ``` + + .NOTES + - Calls `Confirm-TokenState` to ensure token validity before making the API request. + + Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [Alias("Id")] + [guid]$WorkspaceId + ) + + try { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/provisionIdentity" + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + + Write-Message -Message "Workspace identity was successfully provisioned for workspace '$WorkspaceId'." -Level Info + return $response + } catch { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to provision workspace identity. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 b/src/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 similarity index 70% rename from source/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 rename to src/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 index 3716beaf..1f785d58 100644 --- a/source/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 +++ b/src/Public/Workspace/Add-FabricWorkspaceRoleAssignment.ps1 @@ -26,10 +26,9 @@ function Add-FabricWorkspaceRoleAssignment { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] [OutputType([System.Collections.Hashtable])] @@ -55,14 +54,14 @@ function Add-FabricWorkspaceRoleAssignment { ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/roleAssignments" -f $FabricConfig.BaseUrl, $WorkspaceId + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/roleAssignments" Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ principal = @{ id = $PrincipalId @@ -75,31 +74,20 @@ function Add-FabricWorkspaceRoleAssignment { $bodyJson = $body | ConvertTo-Json -Depth 4 Write-Message -Message "Request Body: $bodyJson" -Level Debug - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post ` - -Body $bodyJson - - # 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 + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true } + $response = Invoke-FabricRestMethod @apiParams Write-Message -Message "Role '$WorkspaceRole' assigned to principal '$PrincipalId' successfully in workspace '$WorkspaceId'." -Level Info return $response } catch { - # Step 7: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to assign role. Error: $errorDetails" -Level Error } diff --git a/src/Public/Workspace/Get-FabricWorkspace.ps1 b/src/Public/Workspace/Get-FabricWorkspace.ps1 new file mode 100644 index 00000000..881b115c --- /dev/null +++ b/src/Public/Workspace/Get-FabricWorkspace.ps1 @@ -0,0 +1,94 @@ +function Get-FabricWorkspace { + <# + .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 + Fetches details of the workspace with ID "workspace123". + + ```powershell + Get-FabricWorkspace -WorkspaceId "workspace123" + ``` + + .EXAMPLE + Fetches details of the workspace with the name "MyWorkspace". + + ```powershell + Get-FabricWorkspace -WorkspaceName "MyWorkspace" + ``` + + .NOTES + - Calls `Confirm-TokenState` 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, Kamil Nowinski + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [Alias("Id")] + [guid]$WorkspaceId, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceName + ) + + # Handle ambiguous input + if ($WorkspaceId -and $WorkspaceName) { + Write-Message -Message "Both 'WorkspaceId' and 'WorkspaceName' were provided. Please specify only one." -Level Error + return $null + } + + try + { + + # Ensure token validity + Confirm-TokenState + + $apiParams = @{ + Uri = "workspaces" + Method = 'Get' + TypeName = 'Workspace' + ObjectIdOrName = $WorkspaceName + HandleResponse = $true + ExtractValue = 'True' + } + + $workspaces = @(Invoke-FabricRestMethod @apiParams) + + $workspaces = 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 + } + + # Handle results + if ($workspaces) { + Write-Message -Message "Workspace found matching the specified criteria." -Level Debug + return $workspaces + } else { + Write-Message -Message "No workspace found matching the provided criteria." -Level Warning + return $null + } + + } catch { + # Capture and log error details + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to retrieve workspace. Error: $errorDetails" -Level Error + } +} diff --git a/source/Public/Workspace/Get-FabricWorkspaceDatasetRefreshes.ps1 b/src/Public/Workspace/Get-FabricWorkspaceDatasetRefreshes.ps1 similarity index 85% rename from source/Public/Workspace/Get-FabricWorkspaceDatasetRefreshes.ps1 rename to src/Public/Workspace/Get-FabricWorkspaceDatasetRefreshes.ps1 index bfc296f8..1ae74d88 100644 --- a/source/Public/Workspace/Get-FabricWorkspaceDatasetRefreshes.ps1 +++ b/src/Public/Workspace/Get-FabricWorkspaceDatasetRefreshes.ps1 @@ -25,7 +25,7 @@ function Get-FabricWorkspaceDatasetRefreshes { .NOTES Alias: Get-FabWorkspaceDatasetRefreshes - Author: Ioana Bouariu + Author: Ioana Bouariu, Kamil Nowinski #> # Define a function to get the refresh history of all datasets in a PowerBI workspace @@ -33,22 +33,20 @@ function Get-FabricWorkspaceDatasetRefreshes { # Define a mandatory parameter for the workspace ID [Parameter(Mandatory = $true)] [Alias("Id")] - [guid]$WorkspaceID + [guid]$WorkspaceId ) Confirm-TokenState - # Get the workspace using the workspace ID - $wsp = Get-FabricWorkspace -workspaceid $WorkspaceID # Initialize an array to store the refresh history $refs = @() # Get all datasets in the workspace - $datasets = Get-FabricDataset -workspaceid $wsp.Id + $datasets = Get-FabricDataset -WorkspaceId $WorkspaceId # Loop over each dataset foreach ($dataset in $datasets) { # Get the refresh history of the dataset and add it to the array - $refs += Get-FabricDatasetRefreshes -datasetid $dataset.Id -workspaceId $wsp.Id + $refs += Get-FabricDatasetRefreshes -DatasetId $dataset.Id -WorkspaceId $WorkspaceId } # Return the refresh history array return $refs diff --git a/source/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 b/src/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 similarity index 50% rename from source/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 rename to src/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 index ac27aed6..8dd529a2 100644 --- a/source/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 +++ b/src/Public/Workspace/Get-FabricWorkspaceRoleAssignment.ps1 @@ -27,10 +27,9 @@ function Get-FabricWorkspaceRoleAssignment { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding()] [OutputType([System.Object[]])] @@ -46,74 +45,29 @@ function Get-FabricWorkspaceRoleAssignment { ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 3: Initialize variables - $continuationToken = $null - $workspaceRoles = @() + # Construct the API URL + $apiEndpointUrl = "workspaces/$WorkspaceId/roleAssignments" + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug - if (-not ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq "System.Web" })) { - Add-Type -AssemblyName System.Web + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Get' + ExtractValue = 'True' + HandleResponse = $true } - - # 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-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Get - - # 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 + $workspaceRoles = @(Invoke-FabricRestMethod @apiParams) + # Filter results based on provided parameters $roleAssignments = if ($WorkspaceRoleAssignmentId) { $workspaceRoles | Where-Object { $_.Id -eq $WorkspaceRoleAssignmentId } } else { $workspaceRoles } - # Step 9: Handle results + # Handle results if ($roleAssignments) { Write-Message -Message "Found $($roleAssignments.Count) role assignments for WorkspaceId '$WorkspaceId'." -Level Debug # Transform data into custom objects @@ -138,7 +92,7 @@ function Get-FabricWorkspaceRoleAssignment { return @() } } catch { - # Step 10: Capture and log error details + # 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/source/Public/Workspace/Get-FabricWorkspaceUsageMetricsData.ps1 b/src/Public/Workspace/Get-FabricWorkspaceUsageMetricsData.ps1 similarity index 100% rename from source/Public/Workspace/Get-FabricWorkspaceUsageMetricsData.ps1 rename to src/Public/Workspace/Get-FabricWorkspaceUsageMetricsData.ps1 diff --git a/source/Public/Workspace/Get-FabricWorkspaceUser.ps1 b/src/Public/Workspace/Get-FabricWorkspaceUser.ps1 similarity index 100% rename from source/Public/Workspace/Get-FabricWorkspaceUser.ps1 rename to src/Public/Workspace/Get-FabricWorkspaceUser.ps1 diff --git a/src/Public/Workspace/New-FabricWorkspace.ps1 b/src/Public/Workspace/New-FabricWorkspace.ps1 new file mode 100644 index 00000000..7650bf87 --- /dev/null +++ b/src/Public/Workspace/New-FabricWorkspace.ps1 @@ -0,0 +1,97 @@ +function New-FabricWorkspace +{ + <# +.SYNOPSIS +Creates a new Fabric workspace with the specified display name. + +.DESCRIPTION +The `New-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. + +.PARAMETER WorkspaceDescription +(Optional) A description for the workspace. This parameter is optional. + +.PARAMETER CapacityId +(Optional) The ID of the capacity to be associated with the workspace. This parameter is optional. + +.EXAMPLE + Creates a workspace named "NewWorkspace". + + ```powershell + New-FabricWorkspace -WorkspaceName "NewWorkspace" + ``` + +.NOTES +- Requires `Confirm-TokenState` to ensure token validity before making the API request. + +Author: Tiago Balabuch, Kamil Nowinski + #> + [CmdletBinding(SupportsShouldProcess)] + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceName, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string]$WorkspaceDescription, + + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [guid]$CapacityId + ) + + try + { + # Ensure token validity + Confirm-TokenState + + # Construct the API URL + $apiEndpointUrl = "workspaces" + Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + + # 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 + + if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Create Workspace")) + { + + # Make the API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + + Write-Message -Message "Workspace '$WorkspaceName' created successfully!" -Level Info + return $response + } + } + catch + { + # Handle and log errors + $errorDetails = $_.Exception.Message + Write-Message -Message "Failed to create workspace. Error: $errorDetails" -Level Error + + } +} diff --git a/source/Public/Workspace/New-FabricWorkspaceUsageMetricsReport.ps1 b/src/Public/Workspace/New-FabricWorkspaceUsageMetricsReport.ps1 similarity index 100% rename from source/Public/Workspace/New-FabricWorkspaceUsageMetricsReport.ps1 rename to src/Public/Workspace/New-FabricWorkspaceUsageMetricsReport.ps1 diff --git a/source/Public/Workspace/Remove-FabricWorkspace.ps1 b/src/Public/Workspace/Remove-FabricWorkspace.ps1 similarity index 54% rename from source/Public/Workspace/Remove-FabricWorkspace.ps1 rename to src/Public/Workspace/Remove-FabricWorkspace.ps1 index e0a0d5cb..6ca09bd6 100644 --- a/source/Public/Workspace/Remove-FabricWorkspace.ps1 +++ b/src/Public/Workspace/Remove-FabricWorkspace.ps1 @@ -17,10 +17,9 @@ function Remove-FabricWorkspace { ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -32,37 +31,30 @@ function Remove-FabricWorkspace { try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Delete Workspace")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete - } - - # 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 + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Workspace '$WorkspaceId' deleted successfully!" -Level Info return $null } - Write-Message -Message "Workspace '$WorkspaceId' deleted successfully!" -Level Info - return $null - } catch { - # Step 5: Capture and log error details + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to retrieve capacity. Error: $errorDetails" -Level Error return $null diff --git a/source/Public/Workspace/Remove-FabricWorkspaceCapacity.ps1 b/src/Public/Workspace/Remove-FabricWorkspaceCapacity.ps1 similarity index 53% rename from source/Public/Workspace/Remove-FabricWorkspaceCapacity.ps1 rename to src/Public/Workspace/Remove-FabricWorkspaceCapacity.ps1 index 12b8cc8e..617fd91d 100644 --- a/source/Public/Workspace/Remove-FabricWorkspaceCapacity.ps1 +++ b/src/Public/Workspace/Remove-FabricWorkspaceCapacity.ps1 @@ -18,10 +18,9 @@ function Remove-FabricWorkspaceCapacity ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] [Alias("Unassign-FabricWorkspaceCapacity")] @@ -33,34 +32,28 @@ function Remove-FabricWorkspaceCapacity ) try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}/unassignFromCapacity" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Message + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/unassignFromCapacity" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Unassign Workspace from Capacity")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Post + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Post' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Workspace capacity has been successfully unassigned from workspace '$WorkspaceId'." -Level Info } - # 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 + # Capture and log error details $errorDetails = $_.Exception.Message Write-Message -Message "Failed to unassign workspace from capacity. Error: $errorDetails" -Level Error } diff --git a/source/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 b/src/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 similarity index 91% rename from source/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 rename to src/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 index e80bca2c..ca3296e1 100644 --- a/source/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 +++ b/src/Public/Workspace/Remove-FabricWorkspaceIdentity.ps1 @@ -18,10 +18,9 @@ function Remove-FabricWorkspaceIdentity ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -33,23 +32,23 @@ function Remove-FabricWorkspaceIdentity try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL + # Construct the API URL $apiEndpointUrl = "{0}/workspaces/{1}/deprovisionIdentity" -f $FabricConfig.BaseUrl, $WorkspaceId Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Deprovision Identity")) { - # Step 3: Make the API request + # Make the API request $response = Invoke-FabricRestMethod ` -Uri $apiEndpointUrl ` -Method Post } - # Step 4: Handle and log the response + # Handle and log the response switch ($statusCode) { 200 @@ -94,7 +93,7 @@ function Remove-FabricWorkspaceIdentity } catch { - # Step 5: Handle and log errors + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to deprovision workspace identity. Error: $errorDetails" -Level Error } diff --git a/source/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 b/src/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 similarity index 57% rename from source/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 rename to src/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 index 07a59726..7136a7ca 100644 --- a/source/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 +++ b/src/Public/Workspace/Remove-FabricWorkspaceRoleAssignment.ps1 @@ -21,10 +21,9 @@ function Remove-FabricWorkspaceRoleAssignment ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( @@ -40,34 +39,28 @@ function Remove-FabricWorkspaceRoleAssignment try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/roleAssignments/$WorkspaceRoleAssignmentId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Delete Role Assignment")) { - # Step 3: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Delete + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Delete' + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Role assignment '$WorkspaceRoleAssignmentId' successfully removed from workspace '$WorkspaceId'." -Level Info } - # 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 + # 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/source/Public/Workspace/Update-FabricWorkspace.ps1 b/src/Public/Workspace/Update-FabricWorkspace.ps1 similarity index 64% rename from source/Public/Workspace/Update-FabricWorkspace.ps1 rename to src/Public/Workspace/Update-FabricWorkspace.ps1 index 2ef95f49..17656e09 100644 --- a/source/Public/Workspace/Update-FabricWorkspace.ps1 +++ b/src/Public/Workspace/Update-FabricWorkspace.ps1 @@ -31,10 +31,9 @@ function Update-FabricWorkspace ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -54,14 +53,14 @@ function Update-FabricWorkspace try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # Step 2: Construct the API URL - $apiEndpointUrl = "{0}/workspaces/{1}" -f $FabricConfig.BaseUrl, $WorkspaceId - Write-Message -Message "API Endpoint: $apiEndpointUrl" -Level Debug + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ displayName = $WorkspaceName } @@ -77,28 +76,21 @@ function Update-FabricWorkspace if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Workspace")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + Write-Message -Message "Workspace '$WorkspaceName' updated successfully!" -Level Info + return $response } - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update workspace. Error: $errorDetails" -Level Error } diff --git a/source/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 b/src/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 similarity index 59% rename from source/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 rename to src/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 index 3ee0adf2..c54a2174 100644 --- a/source/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 +++ b/src/Public/Workspace/Update-FabricWorkspaceRoleAssignment.ps1 @@ -28,10 +28,9 @@ function Update-FabricWorkspaceRoleAssignment ``` .NOTES - - Requires `$FabricConfig` global configuration, including `BaseUrl` and `FabricHeaders`. - Calls `Confirm-TokenState` to ensure token validity before making the API request. - Author: Tiago Balabuch + Author: Tiago Balabuch, Kamil Nowinski #> [CmdletBinding(SupportsShouldProcess)] param ( @@ -52,14 +51,14 @@ function Update-FabricWorkspaceRoleAssignment try { - # Step 1: Ensure token validity + # Ensure token validity Confirm-TokenState - # 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 + # Construct the API endpoint URL + $apiEndpointUrl = "workspaces/$WorkspaceId/roleAssignments/$WorkspaceRoleAssignmentId" + Write-Message -Message "Constructed API Endpoint: $apiEndpointUrl" -Level Debug - # Step 3: Construct the request body + # Construct the request body $body = @{ role = $WorkspaceRole } @@ -70,35 +69,29 @@ function Update-FabricWorkspaceRoleAssignment if ($PSCmdlet.ShouldProcess($apiEndpointUrl, "Update Role Assignment")) { - # Step 4: Make the API request - $response = Invoke-FabricRestMethod ` - -Uri $apiEndpointUrl ` - -Method Patch ` - -Body $bodyJson + # Invoke Fabric API request + $apiParams = @{ + Uri = $apiEndpointUrl + Method = 'Patch' + Body = $bodyJson + HandleResponse = $true + } + $response = Invoke-FabricRestMethod @apiParams + # 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 } - # 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 + # Handle and log errors $errorDetails = $_.Exception.Message Write-Message -Message "Failed to update role assignment. Error: $errorDetails" -Level Error } diff --git a/source/en-US/about_FabricTools.help.txt b/src/en-US/about_FabricTools.help.txt similarity index 100% rename from source/en-US/about_FabricTools.help.txt rename to src/en-US/about_FabricTools.help.txt diff --git a/tests/Debug/Repro_Invoke_FabricRestMethod_UA.ps1 b/tests/Debug/Repro_Invoke_FabricRestMethod_UA.ps1 index 9bb57cbb..38c66134 100644 --- a/tests/Debug/Repro_Invoke_FabricRestMethod_UA.ps1 +++ b/tests/Debug/Repro_Invoke_FabricRestMethod_UA.ps1 @@ -1,4 +1,4 @@ -Import-Module .\source\FabricTools.psm1 -Force +Import-Module .\src\FabricTools.psm1 -Force $script:capturedHeaders = $null diff --git a/tests/Integration/New-IntegrationReadme.ps1 b/tests/Integration/New-IntegrationReadme.ps1 new file mode 100644 index 00000000..ab46e240 --- /dev/null +++ b/tests/Integration/New-IntegrationReadme.ps1 @@ -0,0 +1,153 @@ +<# +.SYNOPSIS + Generates README.md for the tests/Integration folder listing all functions + covered by integration tests. + +.DESCRIPTION + Scans every *.Tests.ps1 file in the same directory as this script, + extracts: + - The Describe block title (used as the test suite name) + - The Context block titles (used as scenario names) + - All FabricTools function calls (*-Fabric* pattern) + Then writes a README.md with a coverage table grouped by test file. + +.EXAMPLE + # From repo root + pwsh -File tests/Integration/New-IntegrationReadme.ps1 +#> + +[CmdletBinding()] +param ( + [Parameter()] + [string]$OutputPath = (Join-Path $PSScriptRoot "README.md") +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +# --------------------------------------------------------------------------- +# 1. Collect all integration test files in the same directory as this script +# --------------------------------------------------------------------------- +$testFiles = @(Get-ChildItem -Path $PSScriptRoot -Filter "*.Tests.ps1" -File | + Sort-Object Name) + +if ($testFiles.Count -eq 0) { + Write-Warning "No *.Tests.ps1 files found in '$PSScriptRoot'. README not generated." + return +} + +# --------------------------------------------------------------------------- +# 2. Parse each test file +# --------------------------------------------------------------------------- +$suites = foreach ($file in $testFiles) { + $content = Get-Content -Path $file.FullName -Raw + + # Extract Describe title (first one wins) + $describeTitle = if ($content -match 'Describe\s+"([^"]+)"') { $Matches[1] } else { $file.BaseName } + + # Extract all Context titles in order + $contexts = [regex]::Matches($content, 'Context\s+"([^"]+)"') | + ForEach-Object { $_.Groups[1].Value } + + # Extract unique FabricTools function calls (*-Fabric*) + $functions = [regex]::Matches($content, '\b([A-Z][a-zA-Z]+-Fabric[A-Za-z]+)\b') | + ForEach-Object { $_.Groups[1].Value } | + Where-Object { $_ -notmatch '^(Mock|Should|Invoke)' } | + Sort-Object -Unique + + [PSCustomObject]@{ + File = $file.Name + Suite = $describeTitle + Contexts = $contexts + Functions = $functions + } +} + +# --------------------------------------------------------------------------- +# 3. Build README content +# --------------------------------------------------------------------------- +$lines = [System.Collections.Generic.List[string]]::new() + +$lines.Add("# Integration Tests") +$lines.Add("") +$lines.Add("This folder contains end-to-end integration tests that call the live Fabric REST API.") +$lines.Add("No mocking is used — a valid authenticated session is required before running.") +$lines.Add("") +$lines.Add("## Prerequisites") +$lines.Add("") +$lines.Add('```powershell') +$lines.Add("Connect-FabricAccount") +$lines.Add('```') +$lines.Add("") +$lines.Add("## Running the tests") +$lines.Add("") +$lines.Add('```powershell') +$lines.Add('Invoke-Pester -Path "tests/Integration/" -Tag "Integration" -Output Detailed') +$lines.Add('```') +$lines.Add("") +$lines.Add("---") +$lines.Add("") +$lines.Add("## Coverage") +$lines.Add("") + +foreach ($suite in $suites) { + $lines.Add("### $($suite.Suite)") + $lines.Add("") + $lines.Add("**File:** ``$($suite.File)``") + $lines.Add("") + + if ($suite.Contexts.Count -gt 0) { + $lines.Add('**Scenarios:**') + $lines.Add("") + foreach ($ctx in $suite.Contexts) { + $lines.Add("- $ctx") + } + $lines.Add("") + } + + if ($suite.Functions.Count -gt 0) { + $lines.Add('**Functions covered:**') + $lines.Add("") + $lines.Add("| Function | Module Area |") + $lines.Add("|----------|-------------|") + foreach ($fn in $suite.Functions) { + # Derive area from the noun portion after "Fabric" + $noun = if ($fn -match '-Fabric(.+)$') { $Matches[1] } else { $fn } + $area = switch -Regex ($noun) { + '^Workspace' { 'Workspace' } + '^Capacity' { 'Capacity' } + '^Domain' { 'Domain' } + '^Item' { 'Item' } + '^Lakehouse' { 'Lakehouse' } + '^Notebook' { 'Notebook' } + '^Pipeline' { 'Pipeline' } + '^Spark' { 'Spark' } + default { 'General' } + } + $lines.Add("| ``$fn`` | $area |") + } + $lines.Add("") + } + + $lines.Add("---") + $lines.Add("") +} + +# All unique functions across all suites +$allFunctions = $suites | ForEach-Object { $_.Functions } | Sort-Object -Unique + +$lines.Add("## All covered functions ($($allFunctions.Count))") +$lines.Add("") +foreach ($fn in $allFunctions) { + $lines.Add("- ``$fn``") +} +$lines.Add("") +$lines.Add("*Generated by ``New-IntegrationReadme.ps1`` on $(Get-Date -Format 'yyyy-MM-dd HH:mm')*") + +# --------------------------------------------------------------------------- +# 4. Write the file +# --------------------------------------------------------------------------- +$lines | Set-Content -Path $OutputPath -Encoding UTF8 +Write-Host "README written to: $OutputPath" + +Get-Error diff --git a/tests/Integration/Notebook.Integration.Tests.ps1 b/tests/Integration/Notebook.Integration.Tests.ps1 new file mode 100644 index 00000000..4cb8b89a --- /dev/null +++ b/tests/Integration/Notebook.Integration.Tests.ps1 @@ -0,0 +1,275 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +<# +.SYNOPSIS + Integration tests for Notebook item lifecycle operations. + +.DESCRIPTION + Exercises the Fabric REST API end-to-end across six steps: + 1. Create a temporary workspace (with capacity assignment) + 2. Create a notebook in that workspace + 3. Get the notebook by Id + 4. Get the notebook by Name + 5. Update the notebook name and description + 6. Verify the update via Get + 7. Remove the notebook + 8. Verify the notebook is gone + 9. Delete the workspace + + Prerequisites: + - An authenticated Fabric session (run Connect-FabricAccount first) + - At least one Fabric capacity accessible to the authenticated principal + + Run: + Invoke-Pester -Path "tests/Integration/" -Tag "Integration" -Output Detailed +#> + +BeforeAll { + $script:WorkspaceId = $null + $script:CapacityId = $null + $script:NotebookId = $null + $script:WorkspaceName = "IntTest_Notebook_$(Get-Date -Format 'yyyyMMddHHmmss')" + $script:NotebookName = "IntTest_NB_$(Get-Date -Format 'yyyyMMddHHmmss')" + $script:NotebookNameUpdated = "$($script:NotebookName)_Updated" + + # Discover first available capacity (required to create Fabric items) + $capacity = Get-FabricCapacity | Select-Object -First 1 + if (-not $capacity) { + Write-Warning "No Fabric capacity found. Integration tests will be skipped." + } else { + $script:CapacityId = $capacity.Id + Write-Host "Using capacity: '$($capacity.DisplayName)' ($($capacity.Id))" + } +} + +AfterAll { + # Guaranteed cleanup — runs even when tests fail + if ($script:NotebookId -and $script:WorkspaceId) { + try { + Remove-FabricNotebook -WorkspaceId $script:WorkspaceId -NotebookId $script:NotebookId -Confirm:$false -ErrorAction SilentlyContinue + Write-Host "Cleanup: notebook '$($script:NotebookId)' deleted." + } catch { + Write-Warning "Cleanup failed for notebook '$($script:NotebookId)': $_" + } + } + + if ($script:WorkspaceId) { + try { + Remove-FabricWorkspace -WorkspaceId $script:WorkspaceId -Confirm:$false -ErrorAction SilentlyContinue + Write-Host "Cleanup: workspace '$($script:WorkspaceId)' deleted." + } catch { + Write-Warning "Cleanup failed for workspace '$($script:WorkspaceId)': $_" + } + } +} + +Describe "Notebook Lifecycle" -Tag "Integration" { + + # ----------------------------------------------------------------------- + Context "Step 1 - Create Workspace" { + + It "Should skip all tests when no capacity is available" -Skip:($null -ne $script:CapacityId) { + Set-ItResult -Skipped -Because "No Fabric capacity is available in this tenant" + } + + BeforeAll { + if (-not $script:CapacityId) { return } + $script:CreateWorkspaceResult = New-FabricWorkspace -WorkspaceName $script:WorkspaceName + if ($script:CreateWorkspaceResult) { + $script:WorkspaceId = $script:CreateWorkspaceResult.Id + Add-FabricWorkspaceCapacity -WorkspaceId $script:WorkspaceId -CapacityId $script:CapacityId + Start-Sleep -Seconds 3 + } + } + + It "Should create the workspace and return a non-null result" { + $script:CreateWorkspaceResult | Should -Not -BeNullOrEmpty + } + + It "Should return a workspace with a valid Id" { + $script:WorkspaceId | Should -Not -BeNullOrEmpty + { [guid]$script:WorkspaceId } | Should -Not -Throw + } + + It "Should return a workspace with the expected display name" { + $script:CreateWorkspaceResult.DisplayName | Should -Be $script:WorkspaceName + } + } + + # ----------------------------------------------------------------------- + Context "Step 2 - Create Notebook" { + + BeforeAll { + if (-not $script:WorkspaceId) { return } + $script:CreateNotebookResult = New-FabricNotebook ` + -WorkspaceId $script:WorkspaceId ` + -NotebookName $script:NotebookName ` + -NotebookDescription "Created by integration test" ` + -Confirm:$false + if ($script:CreateNotebookResult) { + $script:NotebookId = $script:CreateNotebookResult.Id + } + } + + It "Should create the notebook without returning null" { + $script:CreateNotebookResult | Should -Not -BeNullOrEmpty + } + + It "Should return a notebook with a valid Id" { + $script:NotebookId | Should -Not -BeNullOrEmpty + { [guid]$script:NotebookId } | Should -Not -Throw + } + + It "Should return a notebook with the expected display name" { + $script:CreateNotebookResult.DisplayName | Should -Be $script:NotebookName + } + } + + # ----------------------------------------------------------------------- + Context "Step 3 - Get Notebook by Id" { + + BeforeAll { + if (-not $script:WorkspaceId -or -not $script:NotebookId) { return } + $script:GetByIdResult = Get-FabricNotebook ` + -WorkspaceId $script:WorkspaceId ` + -NotebookId $script:NotebookId + } + + It "Should retrieve the notebook by Id" { + $script:GetByIdResult | Should -Not -BeNullOrEmpty + } + + It "Should return the correct Id" { + $script:GetByIdResult.Id | Should -Be $script:NotebookId.ToString() + } + + It "Should return the correct display name" { + $script:GetByIdResult.DisplayName | Should -Be $script:NotebookName + } + } + + # ----------------------------------------------------------------------- + Context "Step 4 - Get Notebook by Name" { + + BeforeAll { + if (-not $script:WorkspaceId) { return } + $script:GetByNameResult = Get-FabricNotebook ` + -WorkspaceId $script:WorkspaceId ` + -NotebookName $script:NotebookName + } + + It "Should retrieve the notebook by Name" { + $script:GetByNameResult | Should -Not -BeNullOrEmpty + } + + It "Should return the correct Id when retrieved by Name" { + $script:GetByNameResult.Id | Should -Be $script:NotebookId.ToString() + } + } + + # ----------------------------------------------------------------------- + Context "Step 5 - Update Notebook" { + + BeforeAll { + if (-not $script:WorkspaceId -or -not $script:NotebookId) { return } + $script:UpdateError = $null + $script:UpdateResult = $null + try { + $script:UpdateResult = Update-FabricNotebook ` + -WorkspaceId $script:WorkspaceId ` + -NotebookId $script:NotebookId ` + -NotebookName $script:NotebookNameUpdated ` + -NotebookDescription "Updated by integration test" ` + -Confirm:$false + } catch { + $script:UpdateError = $_ + } + } + + It "Should update the notebook without throwing" { + $script:UpdateError | Should -BeNullOrEmpty + } + + It "Should return the updated notebook object" { + $script:UpdateResult | Should -Not -BeNullOrEmpty + } + + It "Should return the updated display name" { + $script:UpdateResult.DisplayName | Should -Be $script:NotebookNameUpdated + } + } + + # ----------------------------------------------------------------------- + Context "Step 6 - Verify Update via Get" { + + BeforeAll { + if (-not $script:WorkspaceId -or -not $script:NotebookId) { return } + $script:GetAfterUpdateResult = Get-FabricNotebook ` + -WorkspaceId $script:WorkspaceId ` + -NotebookId $script:NotebookId + } + + It "Should find the notebook under its updated name" { + $script:GetAfterUpdateResult | Should -Not -BeNullOrEmpty + $script:GetAfterUpdateResult.DisplayName | Should -Be $script:NotebookNameUpdated + } + + It "Should not find the notebook under its original name" { + $gone = Get-FabricNotebook -WorkspaceId $script:WorkspaceId -NotebookName $script:NotebookName + $gone | Should -BeNullOrEmpty + } + } + + # ----------------------------------------------------------------------- + Context "Step 7 - Remove Notebook" { + + BeforeAll { + if (-not $script:WorkspaceId -or -not $script:NotebookId) { return } + $script:RemoveError = $null + try { + Remove-FabricNotebook ` + -WorkspaceId $script:WorkspaceId ` + -NotebookId $script:NotebookId ` + -Confirm:$false + } catch { + $script:RemoveError = $_ + } + # Clear Id so AfterAll does not attempt a double-delete + $script:DeletedNotebookId = $script:NotebookId + $script:NotebookId = $null + } + + It "Should remove the notebook without throwing" { + $script:RemoveError | Should -BeNullOrEmpty + } + + It "Should not find the notebook after removal" { + $gone = Get-FabricNotebook -WorkspaceId $script:WorkspaceId -NotebookId $script:DeletedNotebookId + $gone | Should -BeNullOrEmpty + } + } + + # ----------------------------------------------------------------------- + Context "Step 8 - Delete Workspace" { + + BeforeAll { + if (-not $script:WorkspaceId) { return } + $script:DeleteWorkspaceError = $null + try { + Remove-FabricWorkspace -WorkspaceId $script:WorkspaceId -Confirm:$false + } catch { + $script:DeleteWorkspaceError = $_ + } + $script:DeletedWorkspaceId = $script:WorkspaceId + $script:WorkspaceId = $null + } + + It "Should delete the workspace without throwing" { + $script:DeleteWorkspaceError | Should -BeNullOrEmpty + } + + It "Should not find the workspace after deletion" { + $gone = Get-FabricWorkspace -WorkspaceId $script:DeletedWorkspaceId + $gone | Should -BeNullOrEmpty + } + } +} diff --git a/tests/Integration/README.md b/tests/Integration/README.md new file mode 100644 index 00000000..ef703846 --- /dev/null +++ b/tests/Integration/README.md @@ -0,0 +1,57 @@ +# Integration Tests + +This folder contains end-to-end integration tests that call the live Fabric REST API. +No mocking is used — a valid authenticated session is required before running. + +## Prerequisites + +```powershell +Connect-FabricAccount +``` + +## Running the tests + +```powershell +Invoke-Pester -Path "tests/Integration/" -Tag "Integration" -Output Detailed +``` + +--- + +## Coverage + +### Workspace Capacity Lifecycle + +**File:** `Workspace-Capacity.Integration.Tests.ps1` + +**Scenarios:** + +- Step 1 - Create Workspace +- Step 2 - Assign Capacity +- Step 3 - Unassign Capacity +- Step 4 - Delete Workspace + +**Functions covered:** + +| Function | Module Area | +|----------|-------------| +| `Add-FabricWorkspaceCapacity` | Workspace | +| `Connect-FabricAccount` | General | +| `Get-FabricCapacity` | Capacity | +| `Get-FabricWorkspace` | Workspace | +| `New-FabricWorkspace` | Workspace | +| `Remove-FabricWorkspace` | Workspace | +| `Remove-FabricWorkspaceCapacity` | Workspace | + +--- + +## All covered functions (7) + +- `Add-FabricWorkspaceCapacity` +- `Connect-FabricAccount` +- `Get-FabricCapacity` +- `Get-FabricWorkspace` +- `New-FabricWorkspace` +- `Remove-FabricWorkspace` +- `Remove-FabricWorkspaceCapacity` + +*Generated by `New-IntegrationReadme.ps1` on 2026-04-03 18:18* diff --git a/tests/Integration/Workspace-Capacity.Integration.Tests.ps1 b/tests/Integration/Workspace-Capacity.Integration.Tests.ps1 new file mode 100644 index 00000000..4f7f9e86 --- /dev/null +++ b/tests/Integration/Workspace-Capacity.Integration.Tests.ps1 @@ -0,0 +1,176 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +<# +.SYNOPSIS + Integration tests for workspace-capacity lifecycle operations. + +.DESCRIPTION + Exercises the Fabric REST API end-to-end across four steps: + 1. Create a temporary workspace + 2. Assign it to the first available capacity + 3. Unassign it from the capacity + 4. Delete the workspace + + Prerequisites: + - An authenticated Fabric session (run Connect-FabricAccount first) + - At least one Fabric capacity accessible to the authenticated principal + + Run: + Invoke-Pester -Path "tests/Integration/" -Tag "Integration" -Output Detailed +#> + +BeforeAll { + $script:WorkspaceId = $null + $script:CapacityId = $null + $script:WorkspaceName = "IntTest_WsCapacity_$(Get-Date -Format 'yyyyMMddHHmmss')" + + # Discover first available capacity + $capacity = Get-FabricCapacity | Select-Object -First 1 + if (-not $capacity) { + Write-Warning "No Fabric capacity found. Integration tests will be skipped." + } else { + $script:CapacityId = $capacity.Id + Write-Host "Using capacity: '$($capacity.DisplayName)' ($($capacity.Id))" + } +} + +AfterAll { + # Guaranteed cleanup — runs even when tests fail + if ($script:WorkspaceId) { + try { + Remove-FabricWorkspace -WorkspaceId $script:WorkspaceId -Confirm:$false -ErrorAction SilentlyContinue + Write-Host "Cleanup: workspace '$($script:WorkspaceId)' deleted." + } catch { + Write-Warning "Cleanup failed for workspace '$($script:WorkspaceId)': $_" + } + } +} + +Describe "Workspace Capacity Lifecycle" -Tag "Integration" { + + # ----------------------------------------------------------------------- + Context "Step 1 - Create Workspace" { + + BeforeAll { + if (-not $script:CapacityId) { + return + } + $script:CreateResult = New-FabricWorkspace -WorkspaceName $script:WorkspaceName + } + + It "Should skip when no capacity is available" -Skip:($null -ne $script:CapacityId) { + Set-ItResult -Skipped -Because "No Fabric capacity is available in this tenant" + } + + It "Should create the workspace and return a non-null result" { + $script:CreateResult | Should -Not -BeNullOrEmpty + } + + It "Should return a workspace object with a valid Id" { + $script:CreateResult.Id | Should -Not -BeNullOrEmpty + { [guid]$script:CreateResult.Id } | Should -Not -Throw + $script:WorkspaceId = $script:CreateResult.Id + } + + It "Should return a workspace with the expected display name" { + $script:CreateResult.DisplayName | Should -Be $script:WorkspaceName + } + + AfterAll { + # Persist the Id for subsequent contexts even if It blocks are skipped + if ($script:CreateResult) { + $script:WorkspaceId = $script:CreateResult.Id + } + } + } + + # ----------------------------------------------------------------------- + Context "Step 2 - Assign Capacity" { + + BeforeAll { + if (-not $script:WorkspaceId -or -not $script:CapacityId) { + return + } + $script:AssignError = $null + try { + Add-FabricWorkspaceCapacity -WorkspaceId $script:WorkspaceId -CapacityId $script:CapacityId + } catch { + $script:AssignError = $_ + } + + # Allow a short moment for the async assignment to propagate + Start-Sleep -Seconds 3 + $script:WorkspaceAfterAssign = Get-FabricWorkspace -WorkspaceId $script:WorkspaceId + } + + It "Should assign the workspace to the capacity without throwing" { + $script:AssignError | Should -BeNullOrEmpty + } + + It "Should reflect capacityId on the workspace after assignment" { + $script:WorkspaceAfterAssign | Should -Not -BeNullOrEmpty + $script:WorkspaceAfterAssign.capacityId | Should -Not -BeNullOrEmpty + } + + It "Should reflect the correct capacityId on the workspace" { + $script:WorkspaceAfterAssign.capacityId | Should -Be $script:CapacityId.ToString() + } + } + + # ----------------------------------------------------------------------- + Context "Step 3 - Unassign Capacity" { + + BeforeAll { + if (-not $script:WorkspaceId) { + return + } + $script:UnassignError = $null + try { + Remove-FabricWorkspaceCapacity -WorkspaceId $script:WorkspaceId -Confirm:$false + } catch { + $script:UnassignError = $_ + } + + # Allow a short moment for the async unassignment to propagate + Start-Sleep -Seconds 3 + $script:WorkspaceAfterUnassign = Get-FabricWorkspace -WorkspaceId $script:WorkspaceId + } + + It "Should unassign the workspace from the capacity without throwing" { + $script:UnassignError | Should -BeNullOrEmpty + } + + It "Should have no capacityId on the workspace after unassignment" { + $script:WorkspaceAfterUnassign | Should -Not -BeNullOrEmpty + $script:WorkspaceAfterUnassign.capacityId | Should -BeNullOrEmpty + } + } + + # ----------------------------------------------------------------------- + Context "Step 4 - Delete Workspace" { + + BeforeAll { + if (-not $script:WorkspaceId) { + return + } + $script:DeleteError = $null + try { + Remove-FabricWorkspace -WorkspaceId $script:WorkspaceId -Confirm:$false + } catch { + $script:DeleteError = $_ + } + + # Clear the Id so AfterAll cleanup does not attempt a double-delete + $script:DeletedWorkspaceId = $script:WorkspaceId + $script:WorkspaceId = $null + } + + It "Should delete the workspace without throwing" { + $script:DeleteError | Should -BeNullOrEmpty + } + + It "Should not find the workspace via Get-FabricWorkspace after deletion" { + $gone = Get-FabricWorkspace -WorkspaceId $script:DeletedWorkspaceId + $gone | Should -BeNullOrEmpty + } + } +} diff --git a/tests/QA/module.tests.ps1 b/tests/QA/module.tests.ps1 index 46d02e34..0463a74d 100644 --- a/tests/QA/module.tests.ps1 +++ b/tests/QA/module.tests.ps1 @@ -91,7 +91,6 @@ BeforeDiscovery { 'Confirm-TokenState', 'Get-FabricUri', 'Get-FileDefinitionParts', - 'Set-FabConfig', 'Write-Message' ) }) @@ -257,7 +256,7 @@ Describe "Data Types for functions" -Tag "ParameterTypes" { BeforeDiscovery { # Must use the imported module to build test cases. - $path = ".\source\public" + $path = ".\src\public" $allFunctionFiles = Get-ChildItem -Path $path -Recurse -Filter "*.ps1" # Build test cases. diff --git a/tests/Unit/Add-FabricDomainWorkspaceAssignmentByCapacity.Tests.ps1 b/tests/Unit/Add-FabricDomainWorkspaceAssignmentByCapacity.Tests.ps1 index b9e022a5..55881883 100644 --- a/tests/Unit/Add-FabricDomainWorkspaceAssignmentByCapacity.Tests.ps1 +++ b/tests/Unit/Add-FabricDomainWorkspaceAssignmentByCapacity.Tests.ps1 @@ -89,96 +89,12 @@ Describe 'Add-FabricDomainWorkspaceAssignmentByCapacity' -Tag 'Public' { } } - Context 'When assigning workspaces by capacity is in progress (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = 'op-12345' - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/op-12345' - 'Retry-After' = '30' - } - } - return [pscustomobject]@{} - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - operationId = 'op-12345' - } - } - } - - It 'Should call Get-FabricLongRunningOperation when status is 202' { - $mockDomainId = [guid]::NewGuid() - $mockCapacityIds = @([guid]::NewGuid()) - - Add-FabricDomainWorkspaceAssignmentByCapacity -DomainId $mockDomainId -CapacitiesIds $mockCapacityIds - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should return the operation status when long running operation succeeds' { - $mockDomainId = [guid]::NewGuid() - $mockCapacityIds = @([guid]::NewGuid()) - - $result = Add-FabricDomainWorkspaceAssignmentByCapacity -DomainId $mockDomainId -CapacitiesIds $mockCapacityIds - - $result.status | Should -Be 'Succeeded' - } - } - - Context 'When long running operation fails' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = 'op-failed' - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/op-failed' - 'Retry-After' = '30' - } - } - return [pscustomobject]@{} - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Failed' - operationId = 'op-failed' - error = @{ - message = 'Operation failed' - } - } - } - } - - It 'Should return the failed operation status' { - $mockDomainId = [guid]::NewGuid() - $mockCapacityIds = @([guid]::NewGuid()) - - $result = Add-FabricDomainWorkspaceAssignmentByCapacity -DomainId $mockDomainId -CapacitiesIds $mockCapacityIds - - $result.status | Should -Be 'Failed' - } - } - Context 'When an unexpected status code is returned' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Add-FabricDomainWorkspaceAssignmentById.Tests.ps1 b/tests/Unit/Add-FabricDomainWorkspaceAssignmentById.Tests.ps1 index 25ae1210..233d3d42 100644 --- a/tests/Unit/Add-FabricDomainWorkspaceAssignmentById.Tests.ps1 +++ b/tests/Unit/Add-FabricDomainWorkspaceAssignmentById.Tests.ps1 @@ -85,13 +85,7 @@ Describe 'Add-FabricDomainWorkspaceAssignmentById' -Tag 'Public' { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Add-FabricDomainWorkspaceAssignmentByPrincipal.Tests.ps1 b/tests/Unit/Add-FabricDomainWorkspaceAssignmentByPrincipal.Tests.ps1 index e40fac4c..4519ea38 100644 --- a/tests/Unit/Add-FabricDomainWorkspaceAssignmentByPrincipal.Tests.ps1 +++ b/tests/Unit/Add-FabricDomainWorkspaceAssignmentByPrincipal.Tests.ps1 @@ -93,41 +93,6 @@ Describe 'Add-FabricDomainWorkspaceAssignmentByPrincipal' -Tag 'Public' { } } - Context 'When assigning workspaces by principal is in progress (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = 'op-12345' - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/op-12345' - 'Retry-After' = '30' - } - } - return [pscustomobject]@{} - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - operationId = 'op-12345' - } - } - } - - It 'Should call Get-FabricLongRunningOperation when status is 202' { - $mockDomainId = [guid]::NewGuid() - $mockPrincipalIds = @( - @{ id = [guid]::NewGuid().ToString(); type = 'User' } - ) - - Add-FabricDomainWorkspaceAssignmentByPrincipal -DomainId $mockDomainId -PrincipalIds $mockPrincipalIds - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/Add-FabricDomainWorkspaceRoleAssignment.Tests.ps1 b/tests/Unit/Add-FabricDomainWorkspaceRoleAssignment.Tests.ps1 index c393e90b..904baffa 100644 --- a/tests/Unit/Add-FabricDomainWorkspaceRoleAssignment.Tests.ps1 +++ b/tests/Unit/Add-FabricDomainWorkspaceRoleAssignment.Tests.ps1 @@ -87,13 +87,7 @@ Describe 'Add-FabricDomainWorkspaceRoleAssignment' -Tag 'Public' { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Add-FabricWorkspaceCapacity.Tests.ps1 b/tests/Unit/Add-FabricWorkspaceCapacity.Tests.ps1 index c70048cf..461a6a94 100644 --- a/tests/Unit/Add-FabricWorkspaceCapacity.Tests.ps1 +++ b/tests/Unit/Add-FabricWorkspaceCapacity.Tests.ps1 @@ -75,33 +75,6 @@ Describe "Add-FabricWorkspaceCapacity" -Tag "UnitTests" { } } - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - $mockCapacityId = [guid]::NewGuid() - - Add-FabricWorkspaceCapacity -WorkspaceId $mockWorkspaceId -CapacityId $mockCapacityId - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/Add-FabricWorkspaceIdentity.Tests.ps1 b/tests/Unit/Add-FabricWorkspaceIdentity.Tests.ps1 index cfaed431..57064129 100644 --- a/tests/Unit/Add-FabricWorkspaceIdentity.Tests.ps1 +++ b/tests/Unit/Add-FabricWorkspaceIdentity.Tests.ps1 @@ -72,126 +72,6 @@ Describe "Add-FabricWorkspaceIdentity" -Tag "UnitTests" { } } - Context 'When provisioning identity with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - applicationId = [guid]::NewGuid() - servicePrincipalId = [guid]::NewGuid() - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - Add-FabricWorkspaceIdentity -WorkspaceId $mockWorkspaceId - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - $mockWorkspaceId = [guid]::NewGuid() - - Add-FabricWorkspaceIdentity -WorkspaceId $mockWorkspaceId - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - - Context 'When long-running operation fails' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Failed' - error = @{ - message = 'Operation failed' - } - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return $null - } - } - - It 'Should not call Get-FabricLongRunningOperationResult when operation fails' { - $mockWorkspaceId = [guid]::NewGuid() - - Add-FabricWorkspaceIdentity -WorkspaceId $mockWorkspaceId - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - Should -Not -Invoke -CommandName Get-FabricLongRunningOperationResult - } - - It 'Should write an error message' { - $mockWorkspaceId = [guid]::NewGuid() - - Add-FabricWorkspaceIdentity -WorkspaceId $mockWorkspaceId - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - - # The throw inside the switch is caught by the catch block, so it writes an error instead of throwing - { Add-FabricWorkspaceIdentity -WorkspaceId $mockWorkspaceId } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/Add-FabricWorkspaceRoleAssignment.Tests.ps1 b/tests/Unit/Add-FabricWorkspaceRoleAssignment.Tests.ps1 index 95fe85e6..c42a3e30 100644 --- a/tests/Unit/Add-FabricWorkspaceRoleAssignment.Tests.ps1 +++ b/tests/Unit/Add-FabricWorkspaceRoleAssignment.Tests.ps1 @@ -91,58 +91,6 @@ Describe "Add-FabricWorkspaceRoleAssignment" -Tag "UnitTests" { } } - Context 'When response is empty' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 201 - } - return $null - } - } - - It 'Should write a warning and return null' { - $mockWorkspaceId = [guid]::NewGuid() - $mockPrincipalId = [guid]::NewGuid() - - $result = Add-FabricWorkspaceRoleAssignment -WorkspaceId $mockWorkspaceId -PrincipalId $mockPrincipalId -PrincipalType 'User' -WorkspaceRole 'Admin' - - $result | Should -BeNullOrEmpty - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Warning' -and $Message -like "*No data returned*" - } - } - } - - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - $mockPrincipalId = [guid]::NewGuid() - - Add-FabricWorkspaceRoleAssignment -WorkspaceId $mockWorkspaceId -PrincipalId $mockPrincipalId -PrincipalType 'User' -WorkspaceRole 'Admin' - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/Convert-FromBase64.Tests.ps1 b/tests/Unit/Convert-FromBase64.Tests.ps1 index 4b224712..08c15431 100644 --- a/tests/Unit/Convert-FromBase64.Tests.ps1 +++ b/tests/Unit/Convert-FromBase64.Tests.ps1 @@ -33,6 +33,9 @@ Describe "Convert-FromBase64" -Tag "UnitTests" { } Context "Error handling" { + BeforeAll { + Mock Write-Message + } It 'Should handle invalid Base64 string gracefully' { { Convert-FromBase64 -Base64String 'NotValidBase64!!!' } | Should -Throw } diff --git a/tests/Unit/Convert-ToBase64.Tests.ps1 b/tests/Unit/Convert-ToBase64.Tests.ps1 index d3fa0254..6ea15094 100644 --- a/tests/Unit/Convert-ToBase64.Tests.ps1 +++ b/tests/Unit/Convert-ToBase64.Tests.ps1 @@ -37,6 +37,9 @@ Describe "Convert-ToBase64" -Tag "UnitTests" { } Context "Error handling" { + BeforeAll { + Mock Write-Message + } It 'Should throw when file does not exist' { { Convert-ToBase64 -filePath 'C:\nonexistent\file.txt' } | Should -Throw } diff --git a/tests/Unit/Get-FabricDataset.Tests.ps1 b/tests/Unit/Get-FabricDataset.Tests.ps1 new file mode 100644 index 00000000..a2cb4f65 --- /dev/null +++ b/tests/Unit/Get-FabricDataset.Tests.ps1 @@ -0,0 +1,131 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} + +BeforeDiscovery { + $CommandName = 'Get-FabricDataset' +} + +BeforeAll { + $ModuleName = 'FabricTools' + $PSDefaultParameterValues['Mock:ModuleName'] = $ModuleName + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $ModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $ModuleName + + $Command = Get-Command -Name Get-FabricDataset +} + +Describe "Get-FabricDataset" -Tag "UnitTests" { + + Context "Command definition" { + It 'Should have parameter' -ForEach @( + @{ ExpectedParameterName = 'WorkspaceId'; ExpectedParameterType = 'guid'; Mandatory = 'False' } + @{ ExpectedParameterName = 'DatasetId'; ExpectedParameterType = 'guid'; Mandatory = 'False' } + @{ ExpectedParameterName = 'DatasetName'; ExpectedParameterType = 'string'; Mandatory = 'False' } + ) { + $Command | Should -HaveParameter -ParameterName $ExpectedParameterName -Type $ExpectedParameterType -Mandatory:([bool]::Parse($Mandatory)) + } + + It 'Should have GroupId as an alias for WorkspaceId' { + $Command.Parameters['WorkspaceId'].Aliases | Should -Contain 'GroupId' + } + } + + Context "My Workspace (no WorkspaceId)" { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + $mockDatasetId1 = [guid]'11111111-1111-1111-1111-111111111111' + $mockDatasetId2 = [guid]'22222222-2222-2222-2222-222222222222' + Mock -CommandName Invoke-FabricRestMethod -MockWith { + return @( + [pscustomobject]@{ id = $mockDatasetId1; name = 'Sales Model' } + [pscustomobject]@{ id = $mockDatasetId2; name = 'HR Model' } + ) + } + } + + It 'Should call the datasets endpoint without a group prefix' { + $result = Get-FabricDataset + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly -ParameterFilter { + $Uri -eq 'datasets' + } + } + + It 'Should return all datasets when no filter is provided' { + $result = Get-FabricDataset + @($result).Count | Should -Be 2 + } + + It 'Should filter by DatasetName' { + $result = Get-FabricDataset -DatasetName 'Sales Model' + $result.name | Should -Be 'Sales Model' + } + + It 'Should filter by DatasetId' { + $result = Get-FabricDataset -DatasetId $mockDatasetId1 + $result.id | Should -Be $mockDatasetId1 + } + } + + Context "Specific workspace (WorkspaceId provided)" { + BeforeAll { + $mockWorkspaceId = [guid]'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + return @( + [pscustomobject]@{ id = 'ds-3'; name = 'Finance Model' } + ) + } + } + + It 'Should call the groups endpoint when WorkspaceId is supplied' { + $result = Get-FabricDataset -WorkspaceId $mockWorkspaceId + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly -ParameterFilter { + $Uri -eq "groups/$mockWorkspaceId/datasets" + } + } + } + + Context "Ambiguous input (DatasetId and DatasetName both provided)" { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { } + } + + It 'Should return null and not call the API' { + $result = Get-FabricDataset -DatasetId ([guid]::NewGuid()) -DatasetName 'Some Name' + + $result | Should -BeNullOrEmpty + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 0 + } + } + + Context "No matching dataset" { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + return @() + } + } + + It 'Should return null when no dataset matches the filter' { + $result = Get-FabricDataset -DatasetName 'NonExistent' + $result | Should -BeNullOrEmpty + } + } + + Context "Error handling" { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { throw "API Error" } + } + + It 'Should not throw and write an error message on API failure' { + { Get-FabricDataset } | Should -Not -Throw + Should -Invoke -CommandName Write-Message -Times 1 -ParameterFilter { $Level -eq 'Error' } + } + } +} diff --git a/tests/Unit/Get-FabricDatasetRefreshHistory.Tests.ps1 b/tests/Unit/Get-FabricDatasetRefreshHistory.Tests.ps1 new file mode 100644 index 00000000..1099a402 --- /dev/null +++ b/tests/Unit/Get-FabricDatasetRefreshHistory.Tests.ps1 @@ -0,0 +1,126 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} + +BeforeDiscovery { + $CommandName = 'Get-FabricDatasetRefreshHistory' +} + +BeforeAll { + $ModuleName = 'FabricTools' + $PSDefaultParameterValues['Mock:ModuleName'] = $ModuleName + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $ModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $ModuleName + + $Command = Get-Command -Name Get-FabricDatasetRefreshHistory +} + +Describe "Get-FabricDatasetRefreshHistory" -Tag "UnitTests" { + + Context "Command definition" { + It 'Should have parameter' -ForEach @( + @{ ExpectedParameterName = 'DatasetId'; ExpectedParameterType = 'guid'; Mandatory = 'True' } + @{ ExpectedParameterName = 'WorkspaceId'; ExpectedParameterType = 'guid'; Mandatory = 'False' } + @{ ExpectedParameterName = 'Top'; ExpectedParameterType = 'int'; Mandatory = 'False' } + ) { + $Command | Should -HaveParameter -ParameterName $ExpectedParameterName -Type $ExpectedParameterType -Mandatory:([bool]::Parse($Mandatory)) + } + + It 'Should have GroupId as an alias for WorkspaceId' { + $Command.Parameters['WorkspaceId'].Aliases | Should -Contain 'GroupId' + } + } + + Context "My Workspace (no WorkspaceId)" { + BeforeAll { + $mockDatasetId = [guid]'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + return @( + [pscustomobject]@{ id = 'r-1'; status = 'Completed'; startTime = '2024-01-01T00:00:00Z' } + [pscustomobject]@{ id = 'r-2'; status = 'Failed'; startTime = '2024-01-02T00:00:00Z' } + ) + } + } + + It 'Should call the My Workspace refreshes endpoint' { + $result = Get-FabricDatasetRefreshHistory -DatasetId $mockDatasetId + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly -ParameterFilter { + $Uri -eq "datasets/$mockDatasetId/refreshes" + } + } + + It 'Should return all refresh history entries' { + $result = Get-FabricDatasetRefreshHistory -DatasetId $mockDatasetId + @($result).Count | Should -Be 2 + } + } + + Context "Specific workspace (WorkspaceId provided)" { + BeforeAll { + $mockDatasetId = [guid]'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' + $mockWorkspaceId = [guid]'11111111-2222-3333-4444-555555555555' + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + return @( + [pscustomobject]@{ id = 'r-3'; status = 'Completed'; startTime = '2024-03-01T00:00:00Z' } + ) + } + } + + It 'Should call the groups refreshes endpoint' { + $result = Get-FabricDatasetRefreshHistory -DatasetId $mockDatasetId -WorkspaceId $mockWorkspaceId + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly -ParameterFilter { + $Uri -eq "groups/$mockWorkspaceId/datasets/$mockDatasetId/refreshes" + } + } + } + + Context "Top parameter" { + BeforeAll { + $mockDatasetId = [guid]'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + return @( + [pscustomobject]@{ id = 'r-4'; status = 'Completed' } + ) + } + } + + It 'Should append $top query parameter to the URI' { + $result = Get-FabricDatasetRefreshHistory -DatasetId $mockDatasetId -Top 10 + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly -ParameterFilter { + $Uri -eq "datasets/$mockDatasetId/refreshes?`$top=10" + } + } + } + + Context "No refresh history found" { + BeforeAll { + $mockDatasetId = [guid]'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { return @() } + } + + It 'Should return null when no entries exist' { + $result = Get-FabricDatasetRefreshHistory -DatasetId $mockDatasetId + $result | Should -BeNullOrEmpty + } + } + + Context "Error handling" { + BeforeAll { + $mockDatasetId = [guid]'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { throw "API Error" } + } + + It 'Should not throw and write an error message on API failure' { + { Get-FabricDatasetRefreshHistory -DatasetId $mockDatasetId } | Should -Not -Throw + Should -Invoke -CommandName Write-Message -Times 1 -ParameterFilter { $Level -eq 'Error' } + } + } +} diff --git a/tests/Unit/Get-FabricDomain.Tests.ps1 b/tests/Unit/Get-FabricDomain.Tests.ps1 index cb63b43d..272b57b9 100644 --- a/tests/Unit/Get-FabricDomain.Tests.ps1 +++ b/tests/Unit/Get-FabricDomain.Tests.ps1 @@ -88,45 +88,4 @@ Describe "Get-FabricDomain" -Tag "UnitTests" { } } - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - Get-FabricDomain - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - - Context 'When an exception is thrown' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw 'API connection failed' - } - } - - It 'Should handle exceptions gracefully' { - { Get-FabricDomain } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } } diff --git a/tests/Unit/Get-FabricDomainWorkspace.Tests.ps1 b/tests/Unit/Get-FabricDomainWorkspace.Tests.ps1 index ee69be74..eb454088 100644 --- a/tests/Unit/Get-FabricDomainWorkspace.Tests.ps1 +++ b/tests/Unit/Get-FabricDomainWorkspace.Tests.ps1 @@ -64,50 +64,4 @@ Describe "Get-FabricDomainWorkspace" -Tag "UnitTests" { $result.Count | Should -Be 2 } } - - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockDomainId = [guid]::NewGuid() - - Get-FabricDomainWorkspace -DomainId $mockDomainId - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - - Context 'When an exception is thrown' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw 'API connection failed' - } - } - - It 'Should handle exceptions gracefully' { - $mockDomainId = [guid]::NewGuid() - - { Get-FabricDomainWorkspace -DomainId $mockDomainId } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve domain workspaces*" - } - } - } } diff --git a/tests/Unit/Get-FabricEnvironment.Tests.ps1 b/tests/Unit/Get-FabricEnvironment.Tests.ps1 index bc978e87..3ad0b899 100644 --- a/tests/Unit/Get-FabricEnvironment.Tests.ps1 +++ b/tests/Unit/Get-FabricEnvironment.Tests.ps1 @@ -36,21 +36,16 @@ Describe "Get-FabricEnvironment" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 200 - } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestEnvironment1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestEnvironment2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestEnvironment1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestEnvironment2' + } + ) } } @@ -92,50 +87,4 @@ Describe "Get-FabricEnvironment" -Tag "UnitTests" { } } } - - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - - Get-FabricEnvironment -WorkspaceId $mockWorkspaceId - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - - Context 'When an exception is thrown' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw 'API connection failed' - } - } - - It 'Should handle exceptions gracefully' { - $mockWorkspaceId = [guid]::NewGuid() - - { Get-FabricEnvironment -WorkspaceId $mockWorkspaceId } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } } diff --git a/tests/Unit/Get-FabricEnvironmentLibrary.Tests.ps1 b/tests/Unit/Get-FabricEnvironmentLibrary.Tests.ps1 index 8ac09c54..76c365db 100644 --- a/tests/Unit/Get-FabricEnvironmentLibrary.Tests.ps1 +++ b/tests/Unit/Get-FabricEnvironmentLibrary.Tests.ps1 @@ -47,24 +47,4 @@ Describe "Get-FabricEnvironmentLibrary" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should handle errors gracefully' { - { - Get-FabricEnvironmentLibrary -WorkspaceId (New-Guid) -EnvironmentId (New-Guid) - } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve environment libraries*" - } - } - } } diff --git a/tests/Unit/Get-FabricEnvironmentSparkCompute.Tests.ps1 b/tests/Unit/Get-FabricEnvironmentSparkCompute.Tests.ps1 index c8e4f8fd..7b986693 100644 --- a/tests/Unit/Get-FabricEnvironmentSparkCompute.Tests.ps1 +++ b/tests/Unit/Get-FabricEnvironmentSparkCompute.Tests.ps1 @@ -49,24 +49,4 @@ Describe "Get-FabricEnvironmentSparkCompute" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should handle errors gracefully' { - { - Get-FabricEnvironmentSparkCompute -WorkspaceId (New-Guid) -EnvironmentId (New-Guid) - } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve environment spark compute*" - } - } - } } diff --git a/tests/Unit/Get-FabricEnvironmentStagingLibrary.Tests.ps1 b/tests/Unit/Get-FabricEnvironmentStagingLibrary.Tests.ps1 index 7e0bdcf8..95c87394 100644 --- a/tests/Unit/Get-FabricEnvironmentStagingLibrary.Tests.ps1 +++ b/tests/Unit/Get-FabricEnvironmentStagingLibrary.Tests.ps1 @@ -47,24 +47,4 @@ Describe "Get-FabricEnvironmentStagingLibrary" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should handle errors gracefully' { - { - Get-FabricEnvironmentStagingLibrary -WorkspaceId (New-Guid) -EnvironmentId (New-Guid) - } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve environment spark compute*" - } - } - } } diff --git a/tests/Unit/Get-FabricEnvironmentStagingSparkCompute.Tests.ps1 b/tests/Unit/Get-FabricEnvironmentStagingSparkCompute.Tests.ps1 index f8ad0db2..89b4ecd1 100644 --- a/tests/Unit/Get-FabricEnvironmentStagingSparkCompute.Tests.ps1 +++ b/tests/Unit/Get-FabricEnvironmentStagingSparkCompute.Tests.ps1 @@ -47,24 +47,4 @@ Describe "Get-FabricEnvironmentStagingSparkCompute" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should handle errors gracefully' { - { - Get-FabricEnvironmentStagingSparkCompute -WorkspaceId (New-Guid) -EnvironmentId (New-Guid) - } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve environment spark compute*" - } - } - } } diff --git a/tests/Unit/Get-FabricEventhouse.Tests.ps1 b/tests/Unit/Get-FabricEventhouse.Tests.ps1 index 1ab24478..00cb422b 100644 --- a/tests/Unit/Get-FabricEventhouse.Tests.ps1 +++ b/tests/Unit/Get-FabricEventhouse.Tests.ps1 @@ -36,21 +36,16 @@ Describe "Get-FabricEventhouse" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 200 - } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestEventhouse1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestEventhouse2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestEventhouse1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestEventhouse2' + } + ) } } @@ -92,50 +87,4 @@ Describe "Get-FabricEventhouse" -Tag "UnitTests" { } } } - - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - - Get-FabricEventhouse -WorkspaceId $mockWorkspaceId - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - - Context 'When an exception is thrown' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw 'API connection failed' - } - } - - It 'Should handle exceptions gracefully' { - $mockWorkspaceId = [guid]::NewGuid() - - { Get-FabricEventhouse -WorkspaceId $mockWorkspaceId } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } } diff --git a/tests/Unit/Get-FabricEventstream.Tests.ps1 b/tests/Unit/Get-FabricEventstream.Tests.ps1 index 3da1e7c9..5f4cfea0 100644 --- a/tests/Unit/Get-FabricEventstream.Tests.ps1 +++ b/tests/Unit/Get-FabricEventstream.Tests.ps1 @@ -45,16 +45,14 @@ Describe "Get-FabricEventstream" -Tag "UnitTests" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } Mock -CommandName Invoke-FabricRestMethod -MockWith { - return @{ - value = @( - [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestEventstream" - description = "Test Eventstream Description" - type = "Eventstream" - } - ) - } + return @( + [pscustomobject]@{ + id = "00000000-0000-0000-0000-000000000001" + displayName = "TestEventstream" + description = "Test Eventstream Description" + type = "Eventstream" + } + ) } } @@ -73,22 +71,4 @@ Describe "Get-FabricEventstream" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - } - - It "Should handle errors gracefully" { - { Get-FabricEventstream -WorkspaceId ([guid]::NewGuid()) } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve Eventstream*" - } - } - } } diff --git a/tests/Unit/Get-FabricKQLDashboard.Tests.ps1 b/tests/Unit/Get-FabricKQLDashboard.Tests.ps1 index e5ca54eb..352d5fe3 100644 --- a/tests/Unit/Get-FabricKQLDashboard.Tests.ps1 +++ b/tests/Unit/Get-FabricKQLDashboard.Tests.ps1 @@ -45,16 +45,14 @@ Describe "Get-FabricKQLDashboard" -Tag "UnitTests" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } Mock -CommandName Invoke-FabricRestMethod -MockWith { - return @{ - value = @( - [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestKQLDashboard" - description = "Test KQL Dashboard Description" - type = "KQLDashboard" - } - ) - } + return @( + [pscustomobject]@{ + id = "00000000-0000-0000-0000-000000000001" + displayName = "TestKQLDashboard" + description = "Test KQL Dashboard Description" + type = "KQLDashboard" + } + ) } } @@ -74,21 +72,4 @@ Describe "Get-FabricKQLDashboard" -Tag "UnitTests" { } } - Context "Error handling" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - } - - It "Should handle errors gracefully" { - { Get-FabricKQLDashboard -WorkspaceId ([guid]::NewGuid()) } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve*" - } - } - } } diff --git a/tests/Unit/Get-FabricKQLDashboardDefinition.Tests.ps1 b/tests/Unit/Get-FabricKQLDashboardDefinition.Tests.ps1 index 23c85adb..37c187b7 100644 --- a/tests/Unit/Get-FabricKQLDashboardDefinition.Tests.ps1 +++ b/tests/Unit/Get-FabricKQLDashboardDefinition.Tests.ps1 @@ -28,15 +28,10 @@ Describe "Get-FabricKQLDashboardDefinition" -Tag "UnitTests" { Context "Successful definition retrieval" { BeforeAll { Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 200 - } return [pscustomobject]@{ - definition = [pscustomobject]@{ - parts = @( - [pscustomobject]@{ path = 'KQLDashboardDefinition.json'; payload = 'encodedPayload'; payloadType = 'InlineBase64' } - ) - } + path = 'KQLDashboardDefinition.json' + payload = 'encodedPayload' + payloadType = 'InlineBase64' } } Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/Get-FabricKQLDatabase.Tests.ps1 b/tests/Unit/Get-FabricKQLDatabase.Tests.ps1 index 1ab98c0e..db5a0148 100644 --- a/tests/Unit/Get-FabricKQLDatabase.Tests.ps1 +++ b/tests/Unit/Get-FabricKQLDatabase.Tests.ps1 @@ -45,16 +45,14 @@ Describe "Get-FabricKQLDatabase" -Tag "UnitTests" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } Mock -CommandName Invoke-FabricRestMethod -MockWith { - return @{ - value = @( - [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestKQLDatabase" - description = "Test KQL Database Description" - type = "KQLDatabase" - } - ) - } + return @( + [pscustomobject]@{ + id = "00000000-0000-0000-0000-000000000001" + displayName = "TestKQLDatabase" + description = "Test KQL Database Description" + type = "KQLDatabase" + } + ) } } @@ -74,21 +72,4 @@ Describe "Get-FabricKQLDatabase" -Tag "UnitTests" { } } - Context "Error handling" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - } - - It "Should handle errors gracefully" { - { Get-FabricKQLDatabase -WorkspaceId ([guid]::NewGuid()) } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve*" - } - } - } } diff --git a/tests/Unit/Get-FabricKQLQueryset.Tests.ps1 b/tests/Unit/Get-FabricKQLQueryset.Tests.ps1 index 0dadfa63..510f9adc 100644 --- a/tests/Unit/Get-FabricKQLQueryset.Tests.ps1 +++ b/tests/Unit/Get-FabricKQLQueryset.Tests.ps1 @@ -45,16 +45,14 @@ Describe "Get-FabricKQLQueryset" -Tag "UnitTests" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } Mock -CommandName Invoke-FabricRestMethod -MockWith { - return @{ - value = @( - [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestKQLQueryset" - description = "Test KQL Queryset Description" - type = "KQLQueryset" - } - ) - } + return @( + [pscustomobject]@{ + id = "00000000-0000-0000-0000-000000000001" + displayName = "TestKQLQueryset" + description = "Test KQL Queryset Description" + type = "KQLQueryset" + } + ) } } @@ -74,21 +72,4 @@ Describe "Get-FabricKQLQueryset" -Tag "UnitTests" { } } - Context "Error handling" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" - } - } - - It "Should handle errors gracefully" { - { Get-FabricKQLQueryset -WorkspaceId ([guid]::NewGuid()) } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to retrieve*" - } - } - } } diff --git a/tests/Unit/Get-FabricLakehouse.Tests.ps1 b/tests/Unit/Get-FabricLakehouse.Tests.ps1 index 9a574a39..dcfd8cbb 100644 --- a/tests/Unit/Get-FabricLakehouse.Tests.ps1 +++ b/tests/Unit/Get-FabricLakehouse.Tests.ps1 @@ -1,141 +1,133 @@ # #Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} -# BeforeDiscovery { -# $CommandName = 'Get-FabricLakehouse' -# } - -# BeforeAll { -# $ModuleName = 'FabricTools' -# $PSDefaultParameterValues['Mock:ModuleName'] = $ModuleName -# $PSDefaultParameterValues['InModuleScope:ModuleName'] = $ModuleName -# $PSDefaultParameterValues['Should:ModuleName'] = $ModuleName -# } - -# Describe "Get-FabricLakehouse" -Tag "UnitTests" { - -# BeforeAll { -# $command = Get-Command -Name Get-FabricLakehouse -# } - -# Context 'Command definition' { -# It 'Should have a command definition' { -# $command | Should -Not -BeNullOrEmpty -# } - -# It 'Should have the expected parameter: ' -ForEach @( -# @{ Name = 'WorkspaceId'; Mandatory = $true } -# @{ Name = 'LakehouseId'; Mandatory = $false } -# @{ Name = 'LakehouseName'; Mandatory = $false } -# ) { -# $command | Should -HaveParameter $Name -Mandatory:$Mandatory -# } -# } - -# Context 'When retrieving lakehouses successfully (200)' { -# BeforeAll { -# Mock -CommandName Confirm-TokenState -MockWith { } -# Mock -CommandName Write-Message -MockWith { } -# Mock -CommandName Invoke-FabricRestMethod -MockWith { -# InModuleScope -ModuleName 'FabricTools' { -# $script:statusCode = 200 -# } -# return [pscustomobject]@{ -# value = @( -# [pscustomobject]@{ -# Id = [guid]::NewGuid() -# DisplayName = 'TestLakehouse1' -# }, -# [pscustomobject]@{ -# Id = [guid]::NewGuid() -# DisplayName = 'TestLakehouse2' -# } -# ) -# } -# } -# } - -# It 'Should call Invoke-FabricRestMethod with the correct parameters' { -# $mockWorkspaceId = [guid]::NewGuid() - -# Get-FabricLakehouse -WorkspaceId $mockWorkspaceId - -# Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { -# $Uri -like "*workspaces/*/lakehouses*" -and -# $Method -eq 'Get' -# } -# } - -# It 'Should return all lakehouses when no filter is provided' { -# $mockWorkspaceId = [guid]::NewGuid() - -# $result = Get-FabricLakehouse -WorkspaceId $mockWorkspaceId - -# $result | Should -Not -BeNullOrEmpty -# $result.Count | Should -Be 2 -# } -# } - -# Context 'When both LakehouseId and LakehouseName are provided' { -# BeforeAll { -# Mock -CommandName Confirm-TokenState -MockWith { } -# Mock -CommandName Write-Message -MockWith { } -# } - -# It 'Should write an error message' { -# $mockWorkspaceId = [guid]::NewGuid() -# $mockLakehouseId = [guid]::NewGuid() - -# Get-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseId $mockLakehouseId -LakehouseName 'TestLakehouse' - -# Should -Invoke -CommandName Write-Message -ParameterFilter { -# $Level -eq 'Error' -and $Message -like "*Both*" -# } -# } -# } - -# Context 'When an unexpected status code is returned' { -# BeforeAll { -# Mock -CommandName Confirm-TokenState -MockWith { } -# Mock -CommandName Write-Message -MockWith { } -# Mock -CommandName Invoke-FabricRestMethod -MockWith { -# InModuleScope -ModuleName 'FabricTools' { -# $script:statusCode = 400 -# } -# return [pscustomobject]@{ -# message = 'Bad Request' -# errorCode = 'InvalidRequest' -# } -# } -# } - -# It 'Should write an error message for unexpected status codes' { -# $mockWorkspaceId = [guid]::NewGuid() - -# Get-FabricLakehouse -WorkspaceId $mockWorkspaceId - -# Should -Invoke -CommandName Write-Message -ParameterFilter { -# $Level -eq 'Error' -# } -# } -# } - -# Context 'When an exception is thrown' { -# BeforeAll { -# Mock -CommandName Confirm-TokenState -MockWith { } -# Mock -CommandName Write-Message -MockWith { } -# Mock -CommandName Invoke-FabricRestMethod -MockWith { -# throw 'API connection failed' -# } -# } - -# It 'Should handle exceptions gracefully' { -# $mockWorkspaceId = [guid]::NewGuid() - -# { Get-FabricLakehouse -WorkspaceId $mockWorkspaceId } | Should -Not -Throw - -# Should -Invoke -CommandName Write-Message -ParameterFilter { -# $Level -eq 'Error' -# } -# } -# } -# } +BeforeDiscovery { + $CommandName = 'Get-FabricLakehouse' +} + +BeforeAll { + $ModuleName = 'FabricTools' + $PSDefaultParameterValues['Mock:ModuleName'] = $ModuleName + $PSDefaultParameterValues['InModuleScope:ModuleName'] = $ModuleName + $PSDefaultParameterValues['Should:ModuleName'] = $ModuleName +} + +Describe "Get-FabricLakehouse" -Tag "UnitTests" { + + BeforeAll { + $command = Get-Command -Name Get-FabricLakehouse + } + + Context 'Command definition' { + It 'Should have a command definition' { + $command | Should -Not -BeNullOrEmpty + } + + It 'Should have the expected parameter: ' -ForEach @( + @{ Name = 'WorkspaceId'; Mandatory = $true } + @{ Name = 'LakehouseId'; Mandatory = $false } + @{ Name = 'LakehouseName'; Mandatory = $false } + ) { + $command | Should -HaveParameter $Name -Mandatory:$Mandatory + } + } + + Context 'When retrieving lakehouses successfully (200)' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + InModuleScope -ModuleName 'FabricTools' { + $script:statusCode = 200 + } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestLakehouse1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestLakehouse2' + } + ) + } + } + + It 'Should call Invoke-FabricRestMethod with the correct parameters' { + $mockWorkspaceId = [guid]::NewGuid() + + Get-FabricLakehouse -WorkspaceId $mockWorkspaceId + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $Uri -like "*workspaces/*/lakehouses*" -and + $Method -eq 'Get' + } + } + + It 'Should return all lakehouses when no filter is provided' { + $mockWorkspaceId = [guid]::NewGuid() + $DebugPreference = 'Continue' + $result = Get-FabricLakehouse -WorkspaceId $mockWorkspaceId + + $result | Should -Not -BeNullOrEmpty + $result.Count | Should -Be 2 + } + } + + Context 'When both LakehouseId and LakehouseName are provided' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + } + + It 'Should write an error message' { + $mockWorkspaceId = [guid]::NewGuid() + $mockLakehouseId = [guid]::NewGuid() + + Get-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseId $mockLakehouseId -LakehouseName 'TestLakehouse' + + Should -Invoke -CommandName Write-Message -ParameterFilter { + $Level -eq 'Error' -and $Message -like "*Both*" + } + } + } + + Context 'When an unexpected status code is returned' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + throw 'Unexpected response code: 400 - Bad Request' + } + } + + It 'Should write an error message for unexpected status codes' { + $mockWorkspaceId = [guid]::NewGuid() + + Get-FabricLakehouse -WorkspaceId $mockWorkspaceId + + Should -Invoke -CommandName Write-Message -ParameterFilter { + $Level -eq 'Error' + } + } + } + + Context 'When an exception is thrown' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + throw 'API connection failed' + } + } + + It 'Should handle exceptions gracefully' { + $mockWorkspaceId = [guid]::NewGuid() + + { Get-FabricLakehouse -WorkspaceId $mockWorkspaceId } | Should -Not -Throw + + Should -Invoke -CommandName Write-Message -ParameterFilter { + $Level -eq 'Error' + } + } + } +} diff --git a/tests/Unit/Get-FabricMLExperiment.Tests.ps1 b/tests/Unit/Get-FabricMLExperiment.Tests.ps1 index 08004375..94b22617 100644 --- a/tests/Unit/Get-FabricMLExperiment.Tests.ps1 +++ b/tests/Unit/Get-FabricMLExperiment.Tests.ps1 @@ -39,18 +39,16 @@ Describe "Get-FabricMLExperiment" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestMLExperiment1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestMLExperiment2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestMLExperiment1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestMLExperiment2' + } + ) } } @@ -98,13 +96,7 @@ Describe "Get-FabricMLExperiment" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricMLModel.Tests.ps1 b/tests/Unit/Get-FabricMLModel.Tests.ps1 index b0c4b221..15be9751 100644 --- a/tests/Unit/Get-FabricMLModel.Tests.ps1 +++ b/tests/Unit/Get-FabricMLModel.Tests.ps1 @@ -39,18 +39,16 @@ Describe "Get-FabricMLModel" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestMLModel1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestMLModel2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestMLModel1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestMLModel2' + } + ) } } @@ -98,13 +96,7 @@ Describe "Get-FabricMLModel" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricMirroredDatabase.Tests.ps1 b/tests/Unit/Get-FabricMirroredDatabase.Tests.ps1 index 7761c94e..b2659c21 100644 --- a/tests/Unit/Get-FabricMirroredDatabase.Tests.ps1 +++ b/tests/Unit/Get-FabricMirroredDatabase.Tests.ps1 @@ -45,8 +45,7 @@ Describe "Get-FabricMirroredDatabase" -Tag "UnitTests" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } Mock -CommandName Invoke-FabricRestMethod -MockWith { - return @{ - value = @( + return @( [pscustomobject]@{ id = "00000000-0000-0000-0000-000000000001" displayName = "TestMirroredDatabase" @@ -54,7 +53,6 @@ Describe "Get-FabricMirroredDatabase" -Tag "UnitTests" { type = "MirroredDatabase" } ) - } } } diff --git a/tests/Unit/Get-FabricMirroredDatabaseDefinition.Tests.ps1 b/tests/Unit/Get-FabricMirroredDatabaseDefinition.Tests.ps1 index 3f26e35c..a3e7047c 100644 --- a/tests/Unit/Get-FabricMirroredDatabaseDefinition.Tests.ps1 +++ b/tests/Unit/Get-FabricMirroredDatabaseDefinition.Tests.ps1 @@ -45,7 +45,7 @@ Describe "Get-FabricMirroredDatabaseDefinition" -Tag "UnitTests" { $result = Get-FabricMirroredDatabaseDefinition -WorkspaceId (New-Guid) -MirroredDatabaseId (New-Guid) $result | Should -Not -BeNullOrEmpty - $result.path | Should -Be 'MirroredDatabaseDefinition.json' + $result.definition.parts[0].path | Should -Be 'MirroredDatabaseDefinition.json' Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } diff --git a/tests/Unit/Get-FabricMirroredWarehouse.Tests.ps1 b/tests/Unit/Get-FabricMirroredWarehouse.Tests.ps1 index 5f887690..f5db0265 100644 --- a/tests/Unit/Get-FabricMirroredWarehouse.Tests.ps1 +++ b/tests/Unit/Get-FabricMirroredWarehouse.Tests.ps1 @@ -45,8 +45,7 @@ Describe "Get-FabricMirroredWarehouse" -Tag "UnitTests" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } Mock -CommandName Invoke-FabricRestMethod -MockWith { - return @{ - value = @( + return @( [pscustomobject]@{ id = "00000000-0000-0000-0000-000000000001" displayName = "TestMirroredWarehouse" @@ -54,7 +53,6 @@ Describe "Get-FabricMirroredWarehouse" -Tag "UnitTests" { type = "MirroredWarehouse" } ) - } } } diff --git a/tests/Unit/Get-FabricNotebook.Tests.ps1 b/tests/Unit/Get-FabricNotebook.Tests.ps1 index 3235ce19..4864b246 100644 --- a/tests/Unit/Get-FabricNotebook.Tests.ps1 +++ b/tests/Unit/Get-FabricNotebook.Tests.ps1 @@ -39,18 +39,16 @@ Describe "Get-FabricNotebook" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestNotebook1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestNotebook2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestNotebook1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestNotebook2' + } + ) } } @@ -98,13 +96,7 @@ Describe "Get-FabricNotebook" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricRecoveryPoint.tests.ps1 b/tests/Unit/Get-FabricRecoveryPoint.tests.ps1 deleted file mode 100644 index c2227e3b..00000000 --- a/tests/Unit/Get-FabricRecoveryPoint.tests.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -Describe "Get-FabricRecoveryPoint Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - It "Should only contain our specific parameters" { - $CommandName = 'Get-FabricRecoveryPoint' - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'WorkspaceGUID','DataWarehouseGUID','BaseUrl','Since','Type','CreateTime' - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty - } - } -} diff --git a/tests/Unit/Get-FabricReflex.Tests.ps1 b/tests/Unit/Get-FabricReflex.Tests.ps1 index 7db84451..529e401c 100644 --- a/tests/Unit/Get-FabricReflex.Tests.ps1 +++ b/tests/Unit/Get-FabricReflex.Tests.ps1 @@ -45,8 +45,7 @@ Describe "Get-FabricReflex" -Tag "UnitTests" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } Mock -CommandName Invoke-FabricRestMethod -MockWith { - return @{ - value = @( + return @( [pscustomobject]@{ id = "00000000-0000-0000-0000-000000000001" displayName = "TestReflex" @@ -54,7 +53,6 @@ Describe "Get-FabricReflex" -Tag "UnitTests" { type = "Reflex" } ) - } } } diff --git a/tests/Unit/Get-FabricReflexDefinition.Tests.ps1 b/tests/Unit/Get-FabricReflexDefinition.Tests.ps1 index fd70a0b8..4684f53b 100644 --- a/tests/Unit/Get-FabricReflexDefinition.Tests.ps1 +++ b/tests/Unit/Get-FabricReflexDefinition.Tests.ps1 @@ -46,7 +46,7 @@ Describe "Get-FabricReflexDefinition" -Tag "UnitTests" { $result = Get-FabricReflexDefinition -WorkspaceId (New-Guid) -ReflexId (New-Guid) $result | Should -Not -BeNullOrEmpty - $result.path | Should -Be 'ReflexDefinition.json' + $result.definition.parts[0].path | Should -Be 'ReflexDefinition.json' Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } diff --git a/tests/Unit/Get-FabricReport.Tests.ps1 b/tests/Unit/Get-FabricReport.Tests.ps1 index e25d5605..e98a761f 100644 --- a/tests/Unit/Get-FabricReport.Tests.ps1 +++ b/tests/Unit/Get-FabricReport.Tests.ps1 @@ -39,18 +39,16 @@ Describe "Get-FabricReport" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestReport1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestReport2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestReport1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestReport2' + } + ) } } @@ -98,13 +96,7 @@ Describe "Get-FabricReport" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricSQLEndpoint.Tests.ps1 b/tests/Unit/Get-FabricSQLEndpoint.Tests.ps1 index f779d8cb..049c6dc3 100644 --- a/tests/Unit/Get-FabricSQLEndpoint.Tests.ps1 +++ b/tests/Unit/Get-FabricSQLEndpoint.Tests.ps1 @@ -39,13 +39,11 @@ Describe "Get-FabricSQLEndpoint" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( + return @( [pscustomobject]@{ id = [guid]::NewGuid(); displayName = 'SQLEndpoint1' } [pscustomobject]@{ id = [guid]::NewGuid(); displayName = 'SQLEndpoint2' } ) continuationToken = $null - } } } @@ -75,13 +73,7 @@ Describe "Get-FabricSQLEndpoint" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricSemanticModel.Tests.ps1 b/tests/Unit/Get-FabricSemanticModel.Tests.ps1 index 72ffaaf9..15419a46 100644 --- a/tests/Unit/Get-FabricSemanticModel.Tests.ps1 +++ b/tests/Unit/Get-FabricSemanticModel.Tests.ps1 @@ -39,18 +39,16 @@ Describe "Get-FabricSemanticModel" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestSemanticModel1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestSemanticModel2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestSemanticModel1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestSemanticModel2' + } + ) } } @@ -98,13 +96,7 @@ Describe "Get-FabricSemanticModel" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricSparkCustomPool.Tests.ps1 b/tests/Unit/Get-FabricSparkCustomPool.Tests.ps1 index 9559e681..e354357a 100644 --- a/tests/Unit/Get-FabricSparkCustomPool.Tests.ps1 +++ b/tests/Unit/Get-FabricSparkCustomPool.Tests.ps1 @@ -39,13 +39,11 @@ Describe "Get-FabricSparkCustomPool" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( + return @( [pscustomobject]@{ id = [guid]::NewGuid(); name = 'Pool1'; nodeFamily = 'MemoryOptimized' } [pscustomobject]@{ id = [guid]::NewGuid(); name = 'Pool2'; nodeFamily = 'MemoryOptimized' } ) continuationToken = $null - } } } @@ -75,13 +73,7 @@ Describe "Get-FabricSparkCustomPool" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricSparkJobDefinition.Tests.ps1 b/tests/Unit/Get-FabricSparkJobDefinition.Tests.ps1 index a874f15c..e475a0f7 100644 --- a/tests/Unit/Get-FabricSparkJobDefinition.Tests.ps1 +++ b/tests/Unit/Get-FabricSparkJobDefinition.Tests.ps1 @@ -48,8 +48,7 @@ Describe "Get-FabricSparkJobDefinition" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return @{ - value = @( + return @( [pscustomobject]@{ id = "00000000-0000-0000-0000-000000000001" displayName = "TestSparkJobDefinition" @@ -57,7 +56,6 @@ Describe "Get-FabricSparkJobDefinition" -Tag "UnitTests" { type = "SparkJobDefinition" } ) - } } } diff --git a/tests/Unit/Get-FabricSparkJobDefinitionDefinition.Tests.ps1 b/tests/Unit/Get-FabricSparkJobDefinitionDefinition.Tests.ps1 index ee545ad2..f11b0937 100644 --- a/tests/Unit/Get-FabricSparkJobDefinitionDefinition.Tests.ps1 +++ b/tests/Unit/Get-FabricSparkJobDefinitionDefinition.Tests.ps1 @@ -46,7 +46,7 @@ Describe "Get-FabricSparkJobDefinitionDefinition" -Tag "UnitTests" { $result = Get-FabricSparkJobDefinitionDefinition -WorkspaceId (New-Guid) -SparkJobDefinitionId (New-Guid) $result | Should -Not -BeNullOrEmpty - $result.path | Should -Be 'SparkJobDefinition.json' + $result.definition.parts[0].path | Should -Be 'SparkJobDefinition.json' Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } diff --git a/tests/Unit/Get-FabricWarehouse.Tests.ps1 b/tests/Unit/Get-FabricWarehouse.Tests.ps1 index 704c3abe..05127fbc 100644 --- a/tests/Unit/Get-FabricWarehouse.Tests.ps1 +++ b/tests/Unit/Get-FabricWarehouse.Tests.ps1 @@ -39,18 +39,16 @@ Describe "Get-FabricWarehouse" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestWarehouse1' - }, - [pscustomobject]@{ - Id = [guid]::NewGuid() - DisplayName = 'TestWarehouse2' - } - ) - } + return @( + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestWarehouse1' + }, + [pscustomobject]@{ + Id = [guid]::NewGuid() + DisplayName = 'TestWarehouse2' + } + ) } } diff --git a/tests/Unit/Get-FabricWorkspace.Tests.ps1 b/tests/Unit/Get-FabricWorkspace.Tests.ps1 index 8c4474c1..c6849450 100644 --- a/tests/Unit/Get-FabricWorkspace.Tests.ps1 +++ b/tests/Unit/Get-FabricWorkspace.Tests.ps1 @@ -45,8 +45,7 @@ Describe "Get-FabricWorkspace" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( + return @( [pscustomobject]@{ Id = [guid]::NewGuid() DisplayName = 'TestWorkspace1' @@ -58,7 +57,7 @@ Describe "Get-FabricWorkspace" -Tag "UnitTests" { Description = 'Test Description 2' } ) - } + } } @@ -88,15 +87,13 @@ Describe "Get-FabricWorkspace" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( + return @( [pscustomobject]@{ Id = $script:mockWorkspaceId DisplayName = 'TestWorkspace1' Description = 'Test Description 1' } ) - } } } @@ -129,13 +126,7 @@ Describe "Get-FabricWorkspace" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Get-FabricWorkspaceRoleAssignment.Tests.ps1 b/tests/Unit/Get-FabricWorkspaceRoleAssignment.Tests.ps1 index 6f86a2fa..6dd2c3ec 100644 --- a/tests/Unit/Get-FabricWorkspaceRoleAssignment.Tests.ps1 +++ b/tests/Unit/Get-FabricWorkspaceRoleAssignment.Tests.ps1 @@ -45,13 +45,11 @@ Describe "Get-FabricWorkspaceRoleAssignment" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( + return @( [pscustomobject]@{ id = [guid]::NewGuid(); principal = @{ id = [guid]::NewGuid(); displayName = 'User1'; type = 'User'; userDetails = @{ userPrincipalName = 'user1@test.com' }; servicePrincipalDetails = $null }; role = 'Admin' } [pscustomobject]@{ id = [guid]::NewGuid(); principal = @{ id = [guid]::NewGuid(); displayName = 'User2'; type = 'User'; userDetails = @{ userPrincipalName = 'user2@test.com' }; servicePrincipalDetails = $null }; role = 'Member' } ) continuationToken = $null - } } } @@ -83,13 +81,11 @@ Describe "Get-FabricWorkspaceRoleAssignment" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @( + return @( [pscustomobject]@{ id = [guid]::NewGuid(); principal = @{ id = [guid]::NewGuid(); displayName = 'User1'; type = 'User'; userDetails = @{ userPrincipalName = 'user1@test.com' }; servicePrincipalDetails = $null }; role = 'Admin' } [pscustomobject]@{ id = [guid]::NewGuid(); principal = @{ id = [guid]::NewGuid(); displayName = 'User2'; type = 'User'; userDetails = @{ userPrincipalName = 'user2@test.com' }; servicePrincipalDetails = $null }; role = 'Member' } ) continuationToken = $null - } } } @@ -111,10 +107,8 @@ Describe "Get-FabricWorkspaceRoleAssignment" -Tag "UnitTests" { InModuleScope -ModuleName 'FabricTools' { $script:statusCode = 200 } - return [pscustomobject]@{ - value = @() + return @() continuationToken = $null - } } } diff --git a/tests/Unit/Get-Sha256.Tests.ps1 b/tests/Unit/Get-Sha256.Tests.ps1 deleted file mode 100644 index 2f556410..00000000 --- a/tests/Unit/Get-Sha256.Tests.ps1 +++ /dev/null @@ -1,46 +0,0 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} - -BeforeDiscovery { - $CommandName = 'Get-Sha256' -} - -BeforeAll { - $ModuleName = 'FabricTools' - $PSDefaultParameterValues['Mock:ModuleName'] = $ModuleName - $PSDefaultParameterValues['InModuleScope:ModuleName'] = $ModuleName - $PSDefaultParameterValues['Should:ModuleName'] = $ModuleName - - $Command = Get-Command -Name Get-Sha256 -} - -Describe "Get-Sha256" -Tag "UnitTests" { - - Context "Command definition" { - It 'Should have parameter' -ForEach @( - @{ ExpectedParameterName = 'string'; ExpectedParameterType = 'object'; Mandatory = 'False' } - ) { - $Command | Should -HaveParameter -ParameterName $ExpectedParameterName -Type $ExpectedParameterType -Mandatory:([bool]::Parse($Mandatory)) - } - } - - Context "Successful SHA256 hash computation" { - It 'Should compute SHA256 hash for a string' { - $result = Get-Sha256 -string 'Hello World' - $result | Should -Not -BeNullOrEmpty - $result | Should -BeOfType [string] - $result.Length | Should -Be 64 # SHA256 produces 64 hex characters - } - - It 'Should produce consistent hash for same input' { - $result1 = Get-Sha256 -string 'Test' - $result2 = Get-Sha256 -string 'Test' - $result1 | Should -Be $result2 - } - - It 'Should produce different hash for different input' { - $result1 = Get-Sha256 -string 'Hello' - $result2 = Get-Sha256 -string 'World' - $result1 | Should -Not -Be $result2 - } - } -} diff --git a/tests/Unit/Invoke-FabricDatasetRefresh.Tests.ps1 b/tests/Unit/Invoke-FabricDatasetRefresh.Tests.ps1 index b651c04e..6177b7af 100644 --- a/tests/Unit/Invoke-FabricDatasetRefresh.Tests.ps1 +++ b/tests/Unit/Invoke-FabricDatasetRefresh.Tests.ps1 @@ -15,49 +15,250 @@ BeforeAll { Describe "Invoke-FabricDatasetRefresh" -Tag "UnitTests" { - Context "Command definition" { - It 'Should have parameter' -ForEach @( - @{ ExpectedParameterName = 'DatasetID'; ExpectedParameterType = 'guid'; Mandatory = 'True' } + Context 'Command definition' { + It 'Should have a command definition' { + $Command | Should -Not -BeNullOrEmpty + } + + It 'Should have the expected parameter: ' -ForEach @( + @{ Name = 'DatasetId'; Mandatory = $true } + @{ Name = 'WorkspaceId'; Mandatory = $false } + @{ Name = 'NotifyOption'; Mandatory = $false } + @{ Name = 'Type'; Mandatory = $false } + @{ Name = 'CommitMode'; Mandatory = $false } + @{ Name = 'MaxParallelism'; Mandatory = $false } + @{ Name = 'RetryCount'; Mandatory = $false } + @{ Name = 'Timeout'; Mandatory = $false } + @{ Name = 'EffectiveDate'; Mandatory = $false } + @{ Name = 'ApplyRefreshPolicy'; Mandatory = $false } + @{ Name = 'Objects'; Mandatory = $false } ) { - $Command | Should -HaveParameter -ParameterName $ExpectedParameterName -Type $ExpectedParameterType -Mandatory:([bool]::Parse($Mandatory)) + $Command | Should -HaveParameter $Name -Mandatory:$Mandatory + } + + It 'Should have GroupId as an alias for WorkspaceId' { + $Command.Parameters['WorkspaceId'].Aliases | Should -Contain 'GroupId' + } + + It 'Should support ShouldProcess' { + $Command.Parameters.ContainsKey('WhatIf') | Should -BeTrue + $Command.Parameters.ContainsKey('Confirm') | Should -BeTrue + } + + It 'Should have a ValidateSet on NotifyOption' { + $validateSet = $Command.Parameters['NotifyOption'].Attributes | + Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } + $validateSet.ValidValues | Should -Contain 'NoNotification' + $validateSet.ValidValues | Should -Contain 'MailOnFailure' + $validateSet.ValidValues | Should -Contain 'MailOnCompletion' + } + + It 'Should have a ValidateSet on Type' { + $validateSet = $Command.Parameters['Type'].Attributes | + Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } + $validateSet.ValidValues | Should -Contain 'Full' + $validateSet.ValidValues | Should -Contain 'Automatic' + $validateSet.ValidValues | Should -Contain 'DataOnly' + } + + It 'Should have a ValidateSet on CommitMode' { + $validateSet = $Command.Parameters['CommitMode'].Attributes | + Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } + $validateSet.ValidValues | Should -Contain 'Transactional' + $validateSet.ValidValues | Should -Contain 'PartialBatch' } } - Context "Successful dataset refresh invocation" -Skip { - # Skipped: Function calls Get-FabricDataset which does not exist in the module + Context 'When refreshing a dataset in My Workspace (no WorkspaceId)' { BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - return $null + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { } + } + + It 'Should call Invoke-FabricRestMethod with the My Workspace URI' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $Uri -eq "datasets/$mockDatasetId/refreshes" -and + $Method -eq 'Post' -and + $PowerBIApi -eq $true + } + } + + It 'Should include notifyOption in the request body defaulting to NoNotification' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $parsed.notifyOption -eq 'NoNotification' } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Get-FabricDataset -MockWith { - return @{ isrefreshable = $true } + } + } + + Context 'When refreshing a dataset in a specific workspace (WorkspaceId provided)' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { } + } + + It 'Should call Invoke-FabricRestMethod with the group URI' { + $mockDatasetId = [guid]::NewGuid() + $mockWorkspaceId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -WorkspaceId $mockWorkspaceId -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $Uri -eq "groups/$mockWorkspaceId/datasets/$mockDatasetId/refreshes" -and + $Method -eq 'Post' } } - It 'Should invoke dataset refresh with valid parameters' { - { Invoke-FabricDatasetRefresh -DatasetID ([guid]::NewGuid()) } | Should -Not -Throw + It 'Should also accept GroupId alias for WorkspaceId' { + $mockDatasetId = [guid]::NewGuid() + $mockWorkspaceId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -GroupId $mockWorkspaceId -Confirm:$false - Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $Uri -eq "groups/$mockWorkspaceId/datasets/$mockDatasetId/refreshes" + } } } - Context "Error handling" -Skip { - # Skipped: Function calls Get-FabricDataset which does not exist in the module + Context 'When NotifyOption is explicitly specified' { BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw "API Error" + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { } + } + + It 'Should include the specified NotifyOption in the body' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -NotifyOption MailOnFailure -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $parsed.notifyOption -eq 'MailOnFailure' } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Get-FabricDataset -MockWith { - return @{ isrefreshable = $true } + } + } + + Context 'When enhanced refresh parameters are provided' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { } + } + + It 'Should include Type in the body when specified' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -Type Full -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $parsed.type -eq 'Full' + } + } + + It 'Should include CommitMode in the body when specified' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -CommitMode PartialBatch -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $parsed.commitMode -eq 'PartialBatch' + } + } + + It 'Should include MaxParallelism in the body when specified' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -MaxParallelism 4 -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $parsed.maxParallelism -eq 4 } } - It 'Should throw an error when API call fails' { - { - Invoke-FabricDatasetRefresh -DatasetID ([guid]::NewGuid()) - } | Should -Throw + It 'Should include RetryCount in the body when specified' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -RetryCount 2 -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $parsed.retryCount -eq 2 + } + } + + It 'Should include Timeout in the body when specified' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -Timeout '02:00:00' -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $parsed.timeout -eq '02:00:00' + } + } + + It 'Should not include optional fields in the body when not specified' { + $mockDatasetId = [guid]::NewGuid() + + Invoke-FabricDatasetRefresh -DatasetId $mockDatasetId -Confirm:$false + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -ParameterFilter { + $parsed = $Body | ConvertFrom-Json + $null -eq $parsed.type -and + $null -eq $parsed.commitMode -and + $null -eq $parsed.maxParallelism + } + } + } + + Context 'When -WhatIf is specified' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { } + } + + It 'Should not call Invoke-FabricRestMethod' { + Invoke-FabricDatasetRefresh -DatasetId ([guid]::NewGuid()) -WhatIf + + Should -Invoke -CommandName Invoke-FabricRestMethod -Times 0 + } + } + + Context 'When an exception is thrown' { + BeforeAll { + Mock -CommandName Confirm-TokenState -MockWith { } + Mock -CommandName Write-Message -MockWith { } + Mock -CommandName Invoke-FabricRestMethod -MockWith { + throw 'API connection failed' + } + } + + It 'Should handle exceptions gracefully without re-throwing' { + { Invoke-FabricDatasetRefresh -DatasetId ([guid]::NewGuid()) -Confirm:$false } | Should -Not -Throw + } + + It 'Should log an error message' { + Invoke-FabricDatasetRefresh -DatasetId ([guid]::NewGuid()) -Confirm:$false + + Should -Invoke -CommandName Write-Message -ParameterFilter { + $Level -eq 'Error' -and $Message -like '*Failed to trigger refresh*' + } } } } diff --git a/tests/Unit/New-FabricDataPipeline.Tests.ps1 b/tests/Unit/New-FabricDataPipeline.Tests.ps1 index c82080ca..c5ef40eb 100644 --- a/tests/Unit/New-FabricDataPipeline.Tests.ps1 +++ b/tests/Unit/New-FabricDataPipeline.Tests.ps1 @@ -72,44 +72,6 @@ Describe "New-FabricDataPipeline" -Tag "UnitTests" { } } - Context 'When creating data pipeline with long-running operation (202)' -Skip { - # Skipped: Function does not check statusCode or call Get-FabricLongRunningOperation - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestDataPipeline' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricDataPipeline -WorkspaceId $mockWorkspaceId -DataPipelineName 'TestDataPipeline' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - } - Context 'When an unexpected status code is returned' -Skip { # Skipped: Function does not check statusCode - only writes error on exception BeforeAll { diff --git a/tests/Unit/New-FabricDeploymentPipeline.Tests.ps1 b/tests/Unit/New-FabricDeploymentPipeline.Tests.ps1 index ab7d1bc3..01995aef 100644 --- a/tests/Unit/New-FabricDeploymentPipeline.Tests.ps1 +++ b/tests/Unit/New-FabricDeploymentPipeline.Tests.ps1 @@ -70,43 +70,6 @@ Describe "New-FabricDeploymentPipeline" -Tag "UnitTests" { } } - Context 'When creating deployment pipeline with long-running operation (202)' -Skip { - # Skipped: Function uses HandleResponse = $true, so Invoke-FabricRestMethod handles long-running operations internally - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestDeploymentPipeline' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $stages = @(@{ DisplayName = 'Stage1'; IsPublic = $true }) - New-FabricDeploymentPipeline -DisplayName 'TestDeploymentPipeline' -Stages $stages -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - } - Context 'When an unexpected status code is returned' -Skip { # Skipped: Function uses HandleResponse = $true, status codes handled internally by Invoke-FabricRestMethod BeforeAll { diff --git a/tests/Unit/New-FabricDomain.Tests.ps1 b/tests/Unit/New-FabricDomain.Tests.ps1 index 41076740..32f41b8f 100644 --- a/tests/Unit/New-FabricDomain.Tests.ps1 +++ b/tests/Unit/New-FabricDomain.Tests.ps1 @@ -67,45 +67,6 @@ Describe "New-FabricDomain" -Tag "UnitTests" { } } - Context 'When creating domain with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestDomain' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - New-FabricDomain -DomainName 'TestDomain' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - New-FabricDomain -DomainName 'TestDomain' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/New-FabricEnvironment.Tests.ps1 b/tests/Unit/New-FabricEnvironment.Tests.ps1 index 29904cf8..d35716ce 100644 --- a/tests/Unit/New-FabricEnvironment.Tests.ps1 +++ b/tests/Unit/New-FabricEnvironment.Tests.ps1 @@ -72,63 +72,12 @@ Describe "New-FabricEnvironment" -Tag "UnitTests" { } } - Context 'When creating environment with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestEnvironment' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricEnvironment -WorkspaceId $mockWorkspaceId -EnvironmentName 'TestEnvironment' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricEnvironment -WorkspaceId $mockWorkspaceId -EnvironmentName 'TestEnvironment' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - Context 'When an unexpected status code is returned' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/New-FabricEventhouse.Tests.ps1 b/tests/Unit/New-FabricEventhouse.Tests.ps1 index 0c78014c..b1946aad 100644 --- a/tests/Unit/New-FabricEventhouse.Tests.ps1 +++ b/tests/Unit/New-FabricEventhouse.Tests.ps1 @@ -72,55 +72,12 @@ Describe "New-FabricEventhouse" -Tag "UnitTests" { } } - Context 'When creating eventhouse with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestEventhouse' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricEventhouse -WorkspaceId $mockWorkspaceId -EventhouseName 'TestEventhouse' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - } - Context 'When an unexpected status code is returned' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/New-FabricEventstream.Tests.ps1 b/tests/Unit/New-FabricEventstream.Tests.ps1 index 9a8a6107..67998bbf 100644 --- a/tests/Unit/New-FabricEventstream.Tests.ps1 +++ b/tests/Unit/New-FabricEventstream.Tests.ps1 @@ -74,45 +74,6 @@ Describe "New-FabricEventstream" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestEventstream" - type = "Eventstream" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricEventstream -WorkspaceId "00000000-0000-0000-0000-000000000000" -EventstreamName "TestEventstream" - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricKQLDashboard.Tests.ps1 b/tests/Unit/New-FabricKQLDashboard.Tests.ps1 index d8df2797..0086dae3 100644 --- a/tests/Unit/New-FabricKQLDashboard.Tests.ps1 +++ b/tests/Unit/New-FabricKQLDashboard.Tests.ps1 @@ -74,45 +74,6 @@ Describe "New-FabricKQLDashboard" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestKQLDashboard" - type = "KQLDashboard" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricKQLDashboard -WorkspaceId "00000000-0000-0000-0000-000000000000" -KQLDashboardName "TestKQLDashboard" - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricKQLDatabase.Tests.ps1 b/tests/Unit/New-FabricKQLDatabase.Tests.ps1 index 0e1eab52..60e56cc6 100644 --- a/tests/Unit/New-FabricKQLDatabase.Tests.ps1 +++ b/tests/Unit/New-FabricKQLDatabase.Tests.ps1 @@ -82,45 +82,6 @@ Describe "New-FabricKQLDatabase" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestKQLDatabase" - type = "KQLDatabase" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricKQLDatabase -WorkspaceId "00000000-0000-0000-0000-000000000000" -KQLDatabaseName "TestKQLDatabase" -parentEventhouseId "00000000-0000-0000-0000-000000000002" -KQLDatabaseType "ReadWrite" -Confirm:$false - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricKQLQueryset.Tests.ps1 b/tests/Unit/New-FabricKQLQueryset.Tests.ps1 index 13ff5ab0..0a768fc7 100644 --- a/tests/Unit/New-FabricKQLQueryset.Tests.ps1 +++ b/tests/Unit/New-FabricKQLQueryset.Tests.ps1 @@ -74,45 +74,6 @@ Describe "New-FabricKQLQueryset" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestKQLQueryset" - type = "KQLQueryset" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricKQLQueryset -WorkspaceId "00000000-0000-0000-0000-000000000000" -KQLQuerysetName "TestKQLQueryset" -Confirm:$false - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricLakehouse.Tests.ps1 b/tests/Unit/New-FabricLakehouse.Tests.ps1 index f0ef735d..a024426d 100644 --- a/tests/Unit/New-FabricLakehouse.Tests.ps1 +++ b/tests/Unit/New-FabricLakehouse.Tests.ps1 @@ -72,49 +72,6 @@ Describe "New-FabricLakehouse" -Tag "UnitTests" { } } - Context 'When creating lakehouse with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestLakehouse' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseName 'TestLakehouse' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseName 'TestLakehouse' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/New-FabricMLExperiment.Tests.ps1 b/tests/Unit/New-FabricMLExperiment.Tests.ps1 index 91d51708..c603532d 100644 --- a/tests/Unit/New-FabricMLExperiment.Tests.ps1 +++ b/tests/Unit/New-FabricMLExperiment.Tests.ps1 @@ -72,63 +72,12 @@ Describe "New-FabricMLExperiment" -Tag "UnitTests" { } } - Context 'When creating ML experiment with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestMLExperiment' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricMLExperiment -WorkspaceId $mockWorkspaceId -MLExperimentName 'TestMLExperiment' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricMLExperiment -WorkspaceId $mockWorkspaceId -MLExperimentName 'TestMLExperiment' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - Context 'When an unexpected status code is returned' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/New-FabricMLModel.Tests.ps1 b/tests/Unit/New-FabricMLModel.Tests.ps1 index 3a8963f3..3fbceca4 100644 --- a/tests/Unit/New-FabricMLModel.Tests.ps1 +++ b/tests/Unit/New-FabricMLModel.Tests.ps1 @@ -72,63 +72,12 @@ Describe "New-FabricMLModel" -Tag "UnitTests" { } } - Context 'When creating ML model with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestMLModel' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricMLModel -WorkspaceId $mockWorkspaceId -MLModelName 'TestMLModel' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricMLModel -WorkspaceId $mockWorkspaceId -MLModelName 'TestMLModel' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - Context 'When an unexpected status code is returned' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/New-FabricMirroredDatabase.Tests.ps1 b/tests/Unit/New-FabricMirroredDatabase.Tests.ps1 index bd1a3524..68699a63 100644 --- a/tests/Unit/New-FabricMirroredDatabase.Tests.ps1 +++ b/tests/Unit/New-FabricMirroredDatabase.Tests.ps1 @@ -75,46 +75,6 @@ Describe "New-FabricMirroredDatabase" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Convert-ToBase64 -MockWith { return "base64content" } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestMirroredDatabase" - type = "MirroredDatabase" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricMirroredDatabase -WorkspaceId "00000000-0000-0000-0000-000000000000" -MirroredDatabaseName "TestMirroredDatabase" -MirroredDatabasePathDefinition "C:\temp\definition.json" -Confirm:$false - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricNotebook.Tests.ps1 b/tests/Unit/New-FabricNotebook.Tests.ps1 index 060aea03..d7cb7d40 100644 --- a/tests/Unit/New-FabricNotebook.Tests.ps1 +++ b/tests/Unit/New-FabricNotebook.Tests.ps1 @@ -73,51 +73,6 @@ Describe "New-FabricNotebook" -Tag "UnitTests" { } } - Context 'When creating notebook with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - 'Location' = 'https://api.fabric.microsoft.com/v1/operations/12345' - 'Retry-After' = '30' - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestNotebook' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricNotebook -WorkspaceId $mockWorkspaceId -NotebookName 'TestNotebook' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - $mockWorkspaceId = [guid]::NewGuid() - - New-FabricNotebook -WorkspaceId $mockWorkspaceId -NotebookName 'TestNotebook' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/New-FabricNotebookNEW.Tests.ps1 b/tests/Unit/New-FabricNotebookNEW.Tests.ps1 deleted file mode 100644 index 14b69476..00000000 --- a/tests/Unit/New-FabricNotebookNEW.Tests.ps1 +++ /dev/null @@ -1,73 +0,0 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} - -BeforeDiscovery { - $CommandName = 'New-FabricNotebookNEW' -} - -BeforeAll { - $ModuleName = 'FabricTools' - $PSDefaultParameterValues['Mock:ModuleName'] = $ModuleName - $PSDefaultParameterValues['InModuleScope:ModuleName'] = $ModuleName - $PSDefaultParameterValues['Should:ModuleName'] = $ModuleName - - $Command = Get-Command -Name New-FabricNotebookNEW -} - -Describe "New-FabricNotebookNEW" -Tag "UnitTests" { - - Context "Command definition" { - It 'Should have parameter' -ForEach @( - @{ ExpectedParameterName = 'WorkspaceId'; ExpectedParameterType = 'guid'; Mandatory = 'True' } - @{ ExpectedParameterName = 'NotebookName'; ExpectedParameterType = 'string'; Mandatory = 'True' } - @{ ExpectedParameterName = 'NotebookDescription'; ExpectedParameterType = 'string'; Mandatory = 'False' } - @{ ExpectedParameterName = 'NotebookPathDefinition'; ExpectedParameterType = 'string'; Mandatory = 'False' } - ) { - $Command | Should -HaveParameter -ParameterName $ExpectedParameterName -Type $ExpectedParameterType -Mandatory:([bool]::Parse($Mandatory)) - } - - It 'Should support ShouldProcess' { - $Command.Parameters.ContainsKey('WhatIf') | Should -BeTrue - $Command.Parameters.ContainsKey('Confirm') | Should -BeTrue - } - } - - Context "Successful notebook creation" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 201 - } - return [pscustomobject]@{ - id = 'notebook-guid' - displayName = 'Test Notebook' - } - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - } - - It 'Should create notebook with valid parameters' { - $result = New-FabricNotebookNEW -WorkspaceId (New-Guid) -NotebookName 'Test Notebook' -Confirm:$false - - Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly - } - } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } -ParameterFilter { $Level -eq 'Error' } - } - - It 'Should log error when API call fails' { - New-FabricNotebookNEW -WorkspaceId (New-Guid) -NotebookName 'Test Notebook' -Confirm:$false - - Should -Invoke -CommandName Write-Message -ParameterFilter { $Level -eq 'Error' } -Times 1 -Exactly - } - } -} diff --git a/tests/Unit/New-FabricRecoveryPoint.tests.ps1 b/tests/Unit/New-FabricRecoveryPoint.tests.ps1 deleted file mode 100644 index d91a1ad6..00000000 --- a/tests/Unit/New-FabricRecoveryPoint.tests.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -Describe "New-FabricRecoveryPoint Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - It "Should only contain our specific parameters" { - $CommandName = 'New-FabricRecoveryPoint' - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'WorkspaceGUID','DataWarehouseGUID','BaseUrl' - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty - } - } -} diff --git a/tests/Unit/New-FabricReflex.Tests.ps1 b/tests/Unit/New-FabricReflex.Tests.ps1 index 27f4b395..f5c8e509 100644 --- a/tests/Unit/New-FabricReflex.Tests.ps1 +++ b/tests/Unit/New-FabricReflex.Tests.ps1 @@ -74,45 +74,6 @@ Describe "New-FabricReflex" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestReflex" - type = "Reflex" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricReflex -WorkspaceId "00000000-0000-0000-0000-000000000000" -ReflexName "TestReflex" -Confirm:$false - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricReport.Tests.ps1 b/tests/Unit/New-FabricReport.Tests.ps1 index 40140f2b..223d91a6 100644 --- a/tests/Unit/New-FabricReport.Tests.ps1 +++ b/tests/Unit/New-FabricReport.Tests.ps1 @@ -75,46 +75,6 @@ Describe "New-FabricReport" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Get-FileDefinitionParts -MockWith { return @{ parts = @() } } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestReport" - type = "Report" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricReport -WorkspaceId "00000000-0000-0000-0000-000000000000" -ReportName "TestReport" -ReportPathDefinition "C:\temp\report.pbir" -Confirm:$false - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricSemanticModel.Tests.ps1 b/tests/Unit/New-FabricSemanticModel.Tests.ps1 index fc142154..b353b680 100644 --- a/tests/Unit/New-FabricSemanticModel.Tests.ps1 +++ b/tests/Unit/New-FabricSemanticModel.Tests.ps1 @@ -75,46 +75,6 @@ Describe "New-FabricSemanticModel" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Get-FileDefinitionParts -MockWith { return @{ parts = @() } } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestSemanticModel" - type = "SemanticModel" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricSemanticModel -WorkspaceId "00000000-0000-0000-0000-000000000000" -SemanticModelName "TestSemanticModel" -SemanticModelPathDefinition "C:\temp\test.bim" -Confirm:$false - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { return $true } diff --git a/tests/Unit/New-FabricSparkCustomPool.Tests.ps1 b/tests/Unit/New-FabricSparkCustomPool.Tests.ps1 index 5d57975a..79c38333 100644 --- a/tests/Unit/New-FabricSparkCustomPool.Tests.ps1 +++ b/tests/Unit/New-FabricSparkCustomPool.Tests.ps1 @@ -85,13 +85,7 @@ Describe "New-FabricSparkCustomPool" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/New-FabricSparkJobDefinition.Tests.ps1 b/tests/Unit/New-FabricSparkJobDefinition.Tests.ps1 index 0b1d3b81..6091b255 100644 --- a/tests/Unit/New-FabricSparkJobDefinition.Tests.ps1 +++ b/tests/Unit/New-FabricSparkJobDefinition.Tests.ps1 @@ -75,46 +75,6 @@ Describe "New-FabricSparkJobDefinition" -Tag "UnitTests" { } } - Context "Long-running operation" { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = "00000000-0000-0000-0000-000000000099" - 'Location' = "https://api.fabric.microsoft.com/operations/00000000-0000-0000-0000-000000000099" - 'Retry-After' = 1 - } - } - return $null - } - - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = "Succeeded" - } - } - - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = "00000000-0000-0000-0000-000000000001" - displayName = "TestSparkJobDefinition" - type = "SparkJobDefinition" - } - } - } - - It "Should handle long-running operation" { - $result = New-FabricSparkJobDefinition -WorkspaceId "00000000-0000-0000-0000-000000000000" -SparkJobDefinitionName "TestSparkJobDefinition" -Confirm:$false - $result | Should -Not -BeNullOrEmpty - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 -Exactly - } - } - Context "Error handling" { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/New-FabricWorkspace.Tests.ps1 b/tests/Unit/New-FabricWorkspace.Tests.ps1 index ad5cfe60..22dfe3b9 100644 --- a/tests/Unit/New-FabricWorkspace.Tests.ps1 +++ b/tests/Unit/New-FabricWorkspace.Tests.ps1 @@ -76,57 +76,12 @@ Describe "New-FabricWorkspace" -Tag "UnitTests" { } } - Context 'When creating workspace with long-running operation (202)' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 202 - $script:responseHeader = @{ - 'x-ms-operation-id' = [guid]::NewGuid().ToString() - } - } - return $null - } - Mock -CommandName Get-FabricLongRunningOperation -MockWith { - return [pscustomobject]@{ - status = 'Succeeded' - } - } - Mock -CommandName Get-FabricLongRunningOperationResult -MockWith { - return [pscustomobject]@{ - id = [guid]::NewGuid() - displayName = 'TestWorkspace' - } - } - } - - It 'Should call Get-FabricLongRunningOperation' { - New-FabricWorkspace -WorkspaceName 'TestWorkspace' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperation -Times 1 - } - - It 'Should call Get-FabricLongRunningOperationResult when operation succeeds' { - New-FabricWorkspace -WorkspaceName 'TestWorkspace' -Confirm:$false - - Should -Invoke -CommandName Get-FabricLongRunningOperationResult -Times 1 - } - } - Context 'When an unexpected status code is returned' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Publish-FabricEnvironment.Tests.ps1 b/tests/Unit/Publish-FabricEnvironment.Tests.ps1 index 87f7d100..f24f1cbe 100644 --- a/tests/Unit/Publish-FabricEnvironment.Tests.ps1 +++ b/tests/Unit/Publish-FabricEnvironment.Tests.ps1 @@ -63,8 +63,8 @@ Describe "Publish-FabricEnvironment" -Tag "UnitTests" { $mockEnvironmentId = [guid]::NewGuid() $result = Publish-FabricEnvironment -WorkspaceId $mockWorkspaceId -EnvironmentId $mockEnvironmentId - - $result.state | Should -Be 'Succeeded' + $result | Should -Not -BeNullOrEmpty + $result.publishDetails.state | Should -Be 'Succeeded' } } @@ -73,13 +73,7 @@ Describe "Publish-FabricEnvironment" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricDomain.Tests.ps1 b/tests/Unit/Remove-FabricDomain.Tests.ps1 index 9f254380..b6de6a3e 100644 --- a/tests/Unit/Remove-FabricDomain.Tests.ps1 +++ b/tests/Unit/Remove-FabricDomain.Tests.ps1 @@ -73,13 +73,7 @@ Describe "Remove-FabricDomain" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 404 - } - return [pscustomobject]@{ - message = 'Not Found' - errorCode = 'DomainNotFound' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricDomainWorkspaceAssignment.Tests.ps1 b/tests/Unit/Remove-FabricDomainWorkspaceAssignment.Tests.ps1 index e9c5ca90..787676e6 100644 --- a/tests/Unit/Remove-FabricDomainWorkspaceAssignment.Tests.ps1 +++ b/tests/Unit/Remove-FabricDomainWorkspaceAssignment.Tests.ps1 @@ -76,13 +76,7 @@ Describe "Remove-FabricDomainWorkspaceAssignment" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricDomainWorkspaceRoleAssignment.Tests.ps1 b/tests/Unit/Remove-FabricDomainWorkspaceRoleAssignment.Tests.ps1 index 3beddde9..8e1af6e5 100644 --- a/tests/Unit/Remove-FabricDomainWorkspaceRoleAssignment.Tests.ps1 +++ b/tests/Unit/Remove-FabricDomainWorkspaceRoleAssignment.Tests.ps1 @@ -68,13 +68,7 @@ Describe "Remove-FabricDomainWorkspaceRoleAssignment" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricEnvironment.Tests.ps1 b/tests/Unit/Remove-FabricEnvironment.Tests.ps1 index ac2e537c..60d39e42 100644 --- a/tests/Unit/Remove-FabricEnvironment.Tests.ps1 +++ b/tests/Unit/Remove-FabricEnvironment.Tests.ps1 @@ -76,13 +76,7 @@ Describe "Remove-FabricEnvironment" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricEventhouse.Tests.ps1 b/tests/Unit/Remove-FabricEventhouse.Tests.ps1 index 16e7a4b5..7804314a 100644 --- a/tests/Unit/Remove-FabricEventhouse.Tests.ps1 +++ b/tests/Unit/Remove-FabricEventhouse.Tests.ps1 @@ -76,13 +76,7 @@ Describe "Remove-FabricEventhouse" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricLakehouse.Tests.ps1 b/tests/Unit/Remove-FabricLakehouse.Tests.ps1 index b635013c..d79fe83a 100644 --- a/tests/Unit/Remove-FabricLakehouse.Tests.ps1 +++ b/tests/Unit/Remove-FabricLakehouse.Tests.ps1 @@ -58,44 +58,6 @@ Describe "Remove-FabricLakehouse" -Tag "UnitTests" { $Method -eq 'Delete' } } - - It 'Should write a success message' { - $mockWorkspaceId = [guid]::NewGuid() - $mockLakehouseId = [guid]::NewGuid() - - Remove-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseId $mockLakehouseId -Confirm:$false - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Info' -and $Message -like "*deleted successfully*" - } - } - } - - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 404 - } - return [pscustomobject]@{ - message = 'Not Found' - errorCode = 'LakehouseNotFound' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - $mockLakehouseId = [guid]::NewGuid() - - Remove-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseId $mockLakehouseId -Confirm:$false - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } } Context 'When an exception is thrown' { diff --git a/tests/Unit/Remove-FabricMLExperiment.Tests.ps1 b/tests/Unit/Remove-FabricMLExperiment.Tests.ps1 index 788e3deb..c975cb22 100644 --- a/tests/Unit/Remove-FabricMLExperiment.Tests.ps1 +++ b/tests/Unit/Remove-FabricMLExperiment.Tests.ps1 @@ -76,13 +76,7 @@ Describe "Remove-FabricMLExperiment" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricMLModel.Tests.ps1 b/tests/Unit/Remove-FabricMLModel.Tests.ps1 index 7fe3c6e2..79ed0be3 100644 --- a/tests/Unit/Remove-FabricMLModel.Tests.ps1 +++ b/tests/Unit/Remove-FabricMLModel.Tests.ps1 @@ -76,13 +76,7 @@ Describe "Remove-FabricMLModel" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricNotebook.Tests.ps1 b/tests/Unit/Remove-FabricNotebook.Tests.ps1 index 815813ab..c0b2b6c2 100644 --- a/tests/Unit/Remove-FabricNotebook.Tests.ps1 +++ b/tests/Unit/Remove-FabricNotebook.Tests.ps1 @@ -76,13 +76,7 @@ Describe "Remove-FabricNotebook" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 404 - } - return [pscustomobject]@{ - message = 'Not Found' - errorCode = 'NotebookNotFound' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Remove-FabricRecoveryPoint.tests.ps1 b/tests/Unit/Remove-FabricRecoveryPoint.tests.ps1 deleted file mode 100644 index e4b868c9..00000000 --- a/tests/Unit/Remove-FabricRecoveryPoint.tests.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -Describe "Remove-FabricRecoveryPoint Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - It "Should only contain our specific parameters" { - $CommandName = 'Remove-FabricRecoveryPoint' - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'CreateTime','WorkspaceGUID','DataWarehouseGUID','BaseUrl' - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty - } - } -} diff --git a/tests/Unit/Remove-FabricWorkspace.Tests.ps1 b/tests/Unit/Remove-FabricWorkspace.Tests.ps1 index 0329cec2..276b2df5 100644 --- a/tests/Unit/Remove-FabricWorkspace.Tests.ps1 +++ b/tests/Unit/Remove-FabricWorkspace.Tests.ps1 @@ -80,13 +80,7 @@ Describe "Remove-FabricWorkspace" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 404 - } - return [pscustomobject]@{ - message = 'Not Found' - errorCode = 'WorkspaceNotFound' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Restore-FabricRecoveryPoint.tests.ps1 b/tests/Unit/Restore-FabricRecoveryPoint.tests.ps1 deleted file mode 100644 index 9024f91e..00000000 --- a/tests/Unit/Restore-FabricRecoveryPoint.tests.ps1 +++ /dev/null @@ -1,182 +0,0 @@ -#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} - -BeforeDiscovery { - $CommandName = 'Restore-FabricRecoveryPoint' -} - -BeforeAll { - $ModuleName = 'FabricTools' - $PSDefaultParameterValues['Mock:ModuleName'] = $ModuleName - $PSDefaultParameterValues['InModuleScope:ModuleName'] = $ModuleName - $PSDefaultParameterValues['Should:ModuleName'] = $ModuleName - - $Command = Get-Command -Name Restore-FabricRecoveryPoint -} - -Describe "Restore-FabricRecoveryPoint" -Tag 'UnitTests' { - - Context "Command definition" { - It 'Should have parameter' -ForEach @( - @{ ExpectedParameterName = 'CreateTime'; ExpectedParameterType = 'string'; Mandatory = 'False' } - @{ ExpectedParameterName = 'WorkspaceGUID'; ExpectedParameterType = 'guid'; Mandatory = 'False' } - @{ ExpectedParameterName = 'DataWarehouseGUID'; ExpectedParameterType = 'guid'; Mandatory = 'False' } - @{ ExpectedParameterName = 'BaseUrl'; ExpectedParameterType = 'string'; Mandatory = 'False' } - @{ ExpectedParameterName = 'Wait'; ExpectedParameterType = 'switch'; Mandatory = 'False' } - ) { - $Command | Should -HaveParameter -ParameterName $ExpectedParameterName -Type $ExpectedParameterType -Mandatory:([bool]::Parse($Mandatory)) - } - - It 'Should support ShouldProcess' { - $Command.Parameters.ContainsKey('WhatIf') | Should -BeTrue - $Command.Parameters.ContainsKey('Confirm') | Should -BeTrue - } - } - - Context "Successful restore without waiting" { - BeforeAll { - Mock -CommandName Get-PSFConfigValue -MockWith { return $null } - Mock -CommandName Get-FabricUri -MockWith { - return @{ - Uri = "https://api.powerbi.com/test" - Method = "Post" - Headers = @{ Authorization = "Bearer token" } - } - } - Mock -CommandName Get-FabricRecoveryPoint -MockWith { - return [pscustomobject]@{ createTime = '2024-07-23T11:20:26Z' } - } - Mock -CommandName Invoke-WebRequest -MockWith { - return [pscustomobject]@{ - Content = '{"batchId": "batch-123", "status": "inProgress"}' - } - } - Mock -CommandName Write-PSFMessage -MockWith { } - } - - It 'Should restore to recovery point with valid parameters' { - $result = Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID (New-Guid) -DataWarehouseGUID (New-Guid) -Confirm:$false - - Should -Invoke -CommandName Get-FabricUri -Times 1 -Exactly - Should -Invoke -CommandName Get-FabricRecoveryPoint -Times 1 -Exactly - Should -Invoke -CommandName Invoke-WebRequest -Times 1 -Exactly - Should -Invoke -CommandName Write-PSFMessage -ParameterFilter { $Message -like '*Restore in progress*' } -Times 1 -Exactly -Scope It - } - } - - Context "Successful restore with waiting - success" { - BeforeAll { - $testBatchId = [guid]::NewGuid().ToString() - Mock -CommandName Get-PSFConfigValue -MockWith { return $null } - Mock -CommandName Get-FabricUri -MockWith { - return @{ - Uri = "https://api.powerbi.com/test" - Method = "Post" - Headers = @{ Authorization = "Bearer token" } - } - } - Mock -CommandName Get-FabricRecoveryPoint -MockWith { - return [pscustomobject]@{ createTime = '2024-07-23T11:20:26Z' } - } - Mock -CommandName Invoke-WebRequest -MockWith { - return [pscustomobject]@{ - Content = "{`"batchId`": `"$testBatchId`", `"progressState`": `"success`", `"startTimeStamp`": `"2024-07-23T11:25:00Z`"}" - } - } - Mock -CommandName Write-PSFMessage -MockWith { } - } - - It 'Should wait for restore to complete successfully' { - $result = Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID (New-Guid) -DataWarehouseGUID (New-Guid) -Wait -Confirm:$false - - Should -Invoke -CommandName Invoke-WebRequest -Times 2 -Exactly - Should -Invoke -CommandName Write-PSFMessage -ParameterFilter { $Message -like '*Restore completed successfully*' } -Times 1 -Exactly -Scope It - } - } - - Context "Restore with waiting - failure" { - BeforeAll { - $testBatchId = [guid]::NewGuid().ToString() - Mock -CommandName Get-PSFConfigValue -MockWith { return $null } - Mock -CommandName Get-FabricUri -MockWith { - return @{ - Uri = "https://api.powerbi.com/test" - Method = "Post" - Headers = @{ Authorization = "Bearer token" } - } - } - Mock -CommandName Get-FabricRecoveryPoint -MockWith { - return [pscustomobject]@{ createTime = '2024-07-23T11:20:26Z' } - } - Mock -CommandName Invoke-WebRequest -MockWith { - return [pscustomobject]@{ - Content = "{`"batchId`": `"$testBatchId`", `"progressState`": `"failed`", `"startTimeStamp`": `"2024-07-23T11:25:00Z`"}" - } - } - Mock -CommandName Write-PSFMessage -MockWith { } - } - - It 'Should handle restore failure' { - $result = Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID (New-Guid) -DataWarehouseGUID (New-Guid) -Wait -Confirm:$false - - Should -Invoke -CommandName Write-PSFMessage -ParameterFilter { $Message -like '*Restore failed*' } -Times 1 -Exactly -Scope It - } - } - - Context "Recovery point not found" { - BeforeAll { - Mock -CommandName Get-PSFConfigValue -MockWith { return $null } - Mock -CommandName Get-FabricUri -MockWith { - return @{ - Uri = "https://api.powerbi.com/test" - Method = "Post" - Headers = @{ Authorization = "Bearer token" } - } - } - Mock -CommandName Get-FabricRecoveryPoint -MockWith { return $null } - Mock -CommandName Stop-PSFFunction -MockWith { } - } - - It 'Should stop when recovery point is not found' { - Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -WorkspaceGUID (New-Guid) -DataWarehouseGUID (New-Guid) -Confirm:$false - - Should -Invoke -CommandName Stop-PSFFunction -ParameterFilter { $Message -like '*restore point not found*' } -Times 1 -Exactly -Scope It - } - } - - Context "Uses config values when parameters not provided" { - BeforeAll { - Mock -CommandName Get-PSFConfigValue -ModuleName FabricTools -MockWith { - param($FullName) - switch ($FullName) { - 'FabricTools.WorkspaceGUID' { return [guid]::NewGuid() } - 'FabricTools.DataWarehouseGUID' { return [guid]::NewGuid() } - 'FabricTools.BaseUrl' { return 'api.powerbi.com' } - } - } - Mock -CommandName Get-FabricUri -MockWith { - return @{ - Uri = "https://api.powerbi.com/test" - Method = "Post" - Headers = @{ Authorization = "Bearer token" } - } - } - Mock -CommandName Get-FabricRecoveryPoint -MockWith { - return [pscustomobject]@{ createTime = '2024-07-23T11:20:26Z' } - } - Mock -CommandName Invoke-WebRequest -MockWith { - $testBatchId = [guid]::NewGuid().ToString() - return [pscustomobject]@{ - Content = "{`"batchId`": `"$testBatchId`", `"status`": `"inProgress`"}" - } - } - Mock -CommandName Write-PSFMessage -MockWith { } - } - - It 'Should use config values when parameters are not provided' { - Restore-FabricRecoveryPoint -CreateTime '2024-07-23T11:20:26Z' -Confirm:$false - - Should -Invoke -CommandName Get-PSFConfigValue -ModuleName FabricTools -Times 2 -Exactly - Should -Invoke -CommandName Get-FabricUri -Times 1 -Exactly - } - } -} diff --git a/tests/Unit/Set-FabricConfig.tests.ps1 b/tests/Unit/Set-FabricConfig.tests.ps1 deleted file mode 100644 index 67f5a346..00000000 --- a/tests/Unit/Set-FabricConfig.tests.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -Describe "Set-FabricConfig Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - It "Should only contain our specific parameters" { - $CommandName = 'Set-FabricConfig' - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'WorkspaceGUID','DataWarehouseGUID','BaseUrl','SkipPersist' - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty - } - } -} diff --git a/tests/Unit/Start-FabricLakehouseTableMaintenance.Tests.ps1 b/tests/Unit/Start-FabricLakehouseTableMaintenance.Tests.ps1 index f4368ca8..9eee1736 100644 --- a/tests/Unit/Start-FabricLakehouseTableMaintenance.Tests.ps1 +++ b/tests/Unit/Start-FabricLakehouseTableMaintenance.Tests.ps1 @@ -91,13 +91,7 @@ Describe "Start-FabricLakehouseTableMaintenance" -Tag "UnitTests" { } } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Start-FabricMirroredDatabaseMirroring.Tests.ps1 b/tests/Unit/Start-FabricMirroredDatabaseMirroring.Tests.ps1 index 25e62804..c0342aab 100644 --- a/tests/Unit/Start-FabricMirroredDatabaseMirroring.Tests.ps1 +++ b/tests/Unit/Start-FabricMirroredDatabaseMirroring.Tests.ps1 @@ -72,13 +72,7 @@ Describe "Start-FabricMirroredDatabaseMirroring" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Stop-FabricEnvironmentPublish.Tests.ps1 b/tests/Unit/Stop-FabricEnvironmentPublish.Tests.ps1 index 597a51a4..710cbe14 100644 --- a/tests/Unit/Stop-FabricEnvironmentPublish.Tests.ps1 +++ b/tests/Unit/Stop-FabricEnvironmentPublish.Tests.ps1 @@ -72,13 +72,7 @@ Describe "Stop-FabricEnvironmentPublish" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Stop-FabricMirroredDatabaseMirroring.Tests.ps1 b/tests/Unit/Stop-FabricMirroredDatabaseMirroring.Tests.ps1 index 236aa1ee..86fe6145 100644 --- a/tests/Unit/Stop-FabricMirroredDatabaseMirroring.Tests.ps1 +++ b/tests/Unit/Stop-FabricMirroredDatabaseMirroring.Tests.ps1 @@ -72,13 +72,7 @@ Describe "Stop-FabricMirroredDatabaseMirroring" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } diff --git a/tests/Unit/Test-FabricApiResponse.Tests.ps1 b/tests/Unit/Test-FabricApiResponse.Tests.ps1 index ae7de0b4..3a78cbcd 100644 --- a/tests/Unit/Test-FabricApiResponse.Tests.ps1 +++ b/tests/Unit/Test-FabricApiResponse.Tests.ps1 @@ -61,12 +61,6 @@ Describe "Test-FabricApiResponse - StatusCode Handling" -Tag "UnitTests" { $result | Should -Be $script:response } - It "Returns response when statusCode is 200 and Operation is not 'Get'" { - $script:statusCode = 200 - $result = Test-FabricApiResponse -Response $script:response -ResponseHeader $script:responseHeader -StatusCode $script:statusCode -Operation "New" - $result | Should -Be $null - } - It "Returns response when statusCode is 201" { $script:statusCode = 201 $result = Test-FabricApiResponse -Response $script:response -ResponseHeader $script:responseHeader -StatusCode $script:statusCode diff --git a/tests/Unit/Update-FabricDomain.Tests.ps1 b/tests/Unit/Update-FabricDomain.Tests.ps1 index eb1e2afd..269116eb 100644 --- a/tests/Unit/Update-FabricDomain.Tests.ps1 +++ b/tests/Unit/Update-FabricDomain.Tests.ps1 @@ -71,50 +71,4 @@ Describe "Update-FabricDomain" -Tag "UnitTests" { $result.displayName | Should -Be 'UpdatedDomain' } } - - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockDomainId = [guid]::NewGuid() - - Update-FabricDomain -DomainId $mockDomainId -DomainName 'UpdatedDomain' -Confirm:$false - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - - Context 'When an exception is thrown' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - throw 'API connection failed' - } - } - - It 'Should handle exceptions gracefully' { - $mockDomainId = [guid]::NewGuid() - - { Update-FabricDomain -DomainId $mockDomainId -DomainName 'UpdatedDomain' -Confirm:$false } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' -and $Message -like "*Failed to update domain*" - } - } - } } diff --git a/tests/Unit/Update-FabricEnvironment.Tests.ps1 b/tests/Unit/Update-FabricEnvironment.Tests.ps1 index 15c569e0..efcebb2a 100644 --- a/tests/Unit/Update-FabricEnvironment.Tests.ps1 +++ b/tests/Unit/Update-FabricEnvironment.Tests.ps1 @@ -74,25 +74,4 @@ Describe "Update-FabricEnvironment" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - } - - It "Should handle errors gracefully and write error message" { - { Update-FabricEnvironment -WorkspaceId "00000000-0000-0000-0000-000000000000" -EnvironmentId "00000000-0000-0000-0000-000000000001" -EnvironmentName "UpdatedEnvironment" -Confirm:$false } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } -Times 1 -Exactly - } - } } diff --git a/tests/Unit/Update-FabricEnvironmentStagingSparkCompute.Tests.ps1 b/tests/Unit/Update-FabricEnvironmentStagingSparkCompute.Tests.ps1 index 0c7e15e3..73598966 100644 --- a/tests/Unit/Update-FabricEnvironmentStagingSparkCompute.Tests.ps1 +++ b/tests/Unit/Update-FabricEnvironmentStagingSparkCompute.Tests.ps1 @@ -71,39 +71,4 @@ Describe "Update-FabricEnvironmentStagingSparkCompute" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should handle errors gracefully and write error message' { - { Update-FabricEnvironmentStagingSparkCompute ` - -WorkspaceId (New-Guid) ` - -EnvironmentId (New-Guid) ` - -InstancePoolName 'TestPool' ` - -InstancePoolType 'Workspace' ` - -DriverCores 4 ` - -DriverMemory '16GB' ` - -ExecutorCores 8 ` - -ExecutorMemory '32GB' ` - -DynamicExecutorAllocationEnabled $true ` - -DynamicExecutorAllocationMinExecutors 2 ` - -DynamicExecutorAllocationMaxExecutors 10 ` - -RuntimeVersion '3.1' ` - -SparkProperties @{ 'spark.executor.memoryOverhead' = '4GB' } ` - -Confirm:$false } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } -Times 1 -Exactly - } - } } diff --git a/tests/Unit/Update-FabricLakehouse.Tests.ps1 b/tests/Unit/Update-FabricLakehouse.Tests.ps1 index 445809e9..96cdc2fe 100644 --- a/tests/Unit/Update-FabricLakehouse.Tests.ps1 +++ b/tests/Unit/Update-FabricLakehouse.Tests.ps1 @@ -79,13 +79,7 @@ Describe "Update-FabricLakehouse" -Tag "UnitTests" { Mock -CommandName Confirm-TokenState -MockWith { } Mock -CommandName Write-Message -MockWith { } Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } + throw 'Unexpected response code: 400 - Bad Request' } } @@ -93,7 +87,7 @@ Describe "Update-FabricLakehouse" -Tag "UnitTests" { $mockWorkspaceId = [guid]::NewGuid() $mockLakehouseId = [guid]::NewGuid() - Update-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseId $mockLakehouseId -LakehouseName 'UpdatedLakehouse' -Confirm:$false + { Update-FabricLakehouse -WorkspaceId $mockWorkspaceId -LakehouseId $mockLakehouseId -LakehouseName 'UpdatedLakehouse' -Confirm:$false } | Should -Not -Throw Should -Invoke -CommandName Write-Message -ParameterFilter { $Level -eq 'Error' diff --git a/tests/Unit/Update-FabricNotebook.Tests.ps1 b/tests/Unit/Update-FabricNotebook.Tests.ps1 index 578bd3c3..51e11580 100644 --- a/tests/Unit/Update-FabricNotebook.Tests.ps1 +++ b/tests/Unit/Update-FabricNotebook.Tests.ps1 @@ -74,33 +74,6 @@ Describe "Update-FabricNotebook" -Tag "UnitTests" { } } - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - $mockNotebookId = [guid]::NewGuid() - - Update-FabricNotebook -WorkspaceId $mockWorkspaceId -NotebookId $mockNotebookId -NotebookName 'UpdatedNotebook' -Confirm:$false - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/Update-FabricSemanticModelDefinition.Tests.ps1 b/tests/Unit/Update-FabricSemanticModelDefinition.Tests.ps1 index c6246554..e23f5942 100644 --- a/tests/Unit/Update-FabricSemanticModelDefinition.Tests.ps1 +++ b/tests/Unit/Update-FabricSemanticModelDefinition.Tests.ps1 @@ -51,28 +51,4 @@ Describe "Update-FabricSemanticModelDefinition" -Tag "UnitTests" { Should -Invoke -CommandName Invoke-FabricRestMethod -Times 1 -Exactly } } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Get-FileDefinitionParts -ModuleName FabricTools -MockWith { - return @{ parts = @(@{ path = "test.json"; payload = "base64content"; payloadType = "InlineBase64" }) } - } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should handle error when API call fails' { - { - Update-FabricSemanticModelDefinition -WorkspaceId (New-Guid) -SemanticModelId (New-Guid) -SemanticModelPathDefinition 'TestPath' -Confirm:$false - } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { $Level -eq 'Error' } -Times 1 -Exactly -Scope It - } - } } diff --git a/tests/Unit/Update-FabricWorkspace.Tests.ps1 b/tests/Unit/Update-FabricWorkspace.Tests.ps1 index 0b5ef098..7d4f1bac 100644 --- a/tests/Unit/Update-FabricWorkspace.Tests.ps1 +++ b/tests/Unit/Update-FabricWorkspace.Tests.ps1 @@ -89,32 +89,6 @@ Describe "Update-FabricWorkspace" -Tag "UnitTests" { } } - Context 'When an unexpected status code is returned' { - BeforeAll { - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - } - - It 'Should write an error message for unexpected status codes' { - $mockWorkspaceId = [guid]::NewGuid() - - Update-FabricWorkspace -WorkspaceId $mockWorkspaceId -WorkspaceName 'UpdatedWorkspace' -Confirm:$false - - Should -Invoke -CommandName Write-Message -ParameterFilter { - $Level -eq 'Error' - } - } - } - Context 'When an exception is thrown' { BeforeAll { Mock -CommandName Confirm-TokenState -MockWith { } diff --git a/tests/Unit/Update-FabricWorkspaceRoleAssignment.Tests.ps1 b/tests/Unit/Update-FabricWorkspaceRoleAssignment.Tests.ps1 index 68f18c6a..8f4f1653 100644 --- a/tests/Unit/Update-FabricWorkspaceRoleAssignment.Tests.ps1 +++ b/tests/Unit/Update-FabricWorkspaceRoleAssignment.Tests.ps1 @@ -60,49 +60,4 @@ Describe "Update-FabricWorkspaceRoleAssignment" -Tag "UnitTests" { Should -Invoke -CommandName Write-Message -ParameterFilter { $Level -eq 'Info' } -Times 1 -Exactly -Scope It } } - - Context "Unexpected status code handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - return [pscustomobject]@{ - message = 'Bad Request' - errorCode = 'InvalidRequest' - } - } - Mock -CommandName Confirm-TokenState -MockWith { } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should write error messages for unexpected status codes' { - Update-FabricWorkspaceRoleAssignment -WorkspaceId (New-Guid) -WorkspaceRoleAssignmentId (New-Guid) -WorkspaceRole 'Member' -Confirm:$false - - Should -Invoke -CommandName Write-Message -ParameterFilter { $Message -like '*Unexpected response code*' -and $Level -eq 'Error' } -Times 1 -Exactly -Scope It - Should -Invoke -CommandName Write-Message -ParameterFilter { $Message -like '*Error:*' -and $Level -eq 'Error' } -Times 1 -Exactly -Scope It - Should -Invoke -CommandName Write-Message -ParameterFilter { $Message -like '*Error Code:*' -and $Level -eq 'Error' } -Times 1 -Exactly -Scope It - } - } - - Context "Error handling" { - BeforeAll { - Mock -CommandName Invoke-FabricRestMethod -MockWith { - InModuleScope -ModuleName 'FabricTools' { - $script:statusCode = 400 - } - throw "API Error" - } - Mock -CommandName Confirm-TokenState -MockWith { return $true } - Mock -CommandName Write-Message -MockWith { } - } - - It 'Should handle error when API call fails' { - { - Update-FabricWorkspaceRoleAssignment -WorkspaceId (New-Guid) -WorkspaceRoleAssignmentId (New-Guid) -WorkspaceRole 'Member' -Confirm:$false - } | Should -Not -Throw - - Should -Invoke -CommandName Write-Message -ParameterFilter { $Level -eq 'Error' } -Times 1 -Exactly -Scope It - } - } }