Skip to content

Back to the cookbook

Find and replace text across every dashboard you can edit

Replaces a text value in every dashboard the current user can edit, including ones shared with them.

Adam Robertson Dashboards

How it works

  1. Log in and capture the access token.
  2. List all the dashboards the user can see, including shared ones, and parse the IDs from the output.
  3. For each dashboard, call GetDashboard.ps1 to get its summary. This includes lastUpdateId, which identifies the current version of the dashboard's definition.
  4. Call GetDashboardUpdate.ps1 with that update ID to get the full JSON definition.
  5. Check whether FindText appears as a JSON string value, and skip the dashboard if not.
  6. Replace each matching value with ReplaceText.
  7. Write the modified JSON to a temporary file, and call UpdateDashboard.ps1 to post it.
  8. Delete the temporary file.

Warning

This script modifies dashboards in place. Test against a non-production system first, and check the search string is specific enough that it only matches what you intend to change.

It also changes dashboards that other users have shared with you, if you can edit them. To limit what it can change, run it as a user who can edit only the dashboards you mean to update.

Scripts it uses

Before you start

You need:

  • The base URL of the Orbit API (see Find your API URLs)
  • An Orbit username and password for the DataView

This script runs other scripts in the repository, so download all of them and run ModifyAllUserDashboards.ps1 from the Powershell folder. See Get the scripts.

Parameters

Parameter Description
-BaseUrl The base URL of the Orbit API, for example https://example.com/OrbitAPI
-DataViewName The name of the DataView to act on, for example holidays
-Username The username to authenticate with. Every dashboard this user can edit is modified.
-FindText The text value to find. Only JSON string values that match it exactly are replaced.
-ReplaceText The text to replace it with.

Example

PowerShell
.\Workflows\ModifyAllUserDashboards.ps1 `
    -BaseUrl "https://example.com/OrbitAPI" `
    -DataViewName "holidays" `
    -Username "myuser" `
    -FindText "Spring Campaign" `
    -ReplaceText "Summer Campaign"

Example output

PowerShell session
> .\Workflows\ModifyAllUserDashboards.ps1 `
      -BaseUrl "https://example.com/OrbitAPI" `
      -DataViewName "holidays" `
      -Username "myuser" `
      -FindText "Spring Campaign" `
      -ReplaceText "Summer Campaign"

Authenticating as 'myuser' against '...'...
Login successful. Access token obtained.
Getting dashboards for user myuser...
Got 3 dashboards
3 dashboard(s) found. Processing...
  [1] Summary Dashboard - Spring Campaign - no match, skipping.
  [3] Customer Instant Insights - updated.
  [4] Impact Report Last Month - updated.

Done. 2 dashboard(s) updated, 1 skipped.

Notes

  • Capturing script output: Write-Output (pipeline) output from a script is captured when you assign the result to a variable (for example, $json = .\GetDashboard.ps1 ...). Write-Host messages go directly to the console and aren't captured, so status messages from the called scripts still appear on screen while the parent script runs.
  • Temporary files: UpdateDashboard.ps1 takes a file path rather than a raw JSON string, so a temporary file passes the modified definition. The finally block makes sure it's deleted even if UpdateDashboard.ps1 fails.
  • String replacement on raw JSON: the script only replaces JSON string values that match FindText exactly, so it won't change field names or longer strings that contain the text. For more precise control, such as replacing within one specific field, convert the JSON to an object with ConvertFrom-Json, update the property, and convert it back with ConvertTo-Json -Depth 100 before writing the temporary file, as SetDashboardTheme.ps1 does.

Script

The script from the repository at commit b732915. Its built-in help is left out here, because this page shows it above. The download and the copy on GitHub include it.

Warning

Apteco provides these scripts as examples only. They're not officially supported. Review each script and test it on a non-production system before you run it against live data.

PowerShell
param (
    [Parameter(Mandatory = $true)]
    [string]$BaseUrl,

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

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

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

    [Parameter(Mandatory = $true)]
    [string]$ReplaceText
)

# The building-block scripts live one folder up, in the Powershell folder
$scripts = Split-Path -Parent $PSScriptRoot

# Match whole JSON string values only, so the text isn't replaced inside
# field names or longer strings. Both strings are encoded with ConvertTo-Json,
# the same serialiser that produced the dashboard JSON, so special characters
# (quotes, backslashes, tabs, and < > & ' in Windows PowerShell) are escaped
# the same way. ConvertTo-Json also adds the surrounding quotes.
$findPattern = [regex]::Escape((ConvertTo-Json -InputObject $FindText))
$replacement = (ConvertTo-Json -InputObject $ReplaceText).Replace('$', '$$')

# ---------------------------------------------------------------------------
# Step 1: Log in and get an access token
# ---------------------------------------------------------------------------
$token = & "$scripts\Login.ps1" -BaseUrl $BaseUrl -DataViewName $DataViewName -Username $Username

if ([string]::IsNullOrWhiteSpace($token)) {
    Write-Error "Login failed - no token returned."
    exit 1
}

# ---------------------------------------------------------------------------
# Step 2: List all dashboards for this user and parse their IDs
#
# ListDashboards.ps1 writes one line per dashboard in the format:
#   <id>: <title>
# We capture those lines and extract the numeric ID from the start of each.
# ---------------------------------------------------------------------------
$dashboardLines = & "$scripts\Dashboards\ListDashboards.ps1" -BaseUrl $BaseUrl -DataViewName $DataViewName -AccessToken $token

$dashboardIds = @($dashboardLines | ForEach-Object {
    if ($_ -match '^(\d+):') { $Matches[1] }
})

Write-Host "$($dashboardIds.Count) dashboard(s) found. Processing..." -ForegroundColor Cyan

# ---------------------------------------------------------------------------
# Step 3: Process each dashboard
# ---------------------------------------------------------------------------
$modifiedCount = 0
$skippedCount  = 0

foreach ($dashboardId in $dashboardIds) {

    # -- 3a. Get the dashboard summary to find the current lastUpdateId ----------
    #
    # GetDashboard.ps1 outputs the dashboard object as JSON to the pipeline.
    # Write-Host status messages go to the console and aren't captured here.
    $dashboardJson  = & "$scripts\Dashboards\GetDashboard.ps1" `
                        -BaseUrl      $BaseUrl `
                        -DataViewName $DataViewName `
                        -AccessToken  $token `
                        -DashboardId  $dashboardId | Out-String

    $dashboard    = ConvertFrom-Json $dashboardJson
    $lastUpdateId = $dashboard.lastUpdateId
    $title        = $dashboard.title

    # -- 3b. Fetch the full update definition -----------------------------------
    #
    # GetDashboardUpdate.ps1 similarly outputs the update object as JSON.
    $updateJson = & "$scripts\Dashboards\GetDashboardUpdate.ps1" `
                    -BaseUrl           $BaseUrl `
                    -DataViewName      $DataViewName `
                    -AccessToken       $token `
                    -DashboardId       $dashboardId `
                    -DashboardUpdateId $lastUpdateId | Out-String

    # -- 3c. Skip if the text isn't present --------------------------------------
    if ($updateJson -notmatch $findPattern) {
        Write-Host "  [$dashboardId] $title - no match, skipping." -ForegroundColor Gray
        $skippedCount++
        continue
    }

    # -- 3d. Replace the text ----------------------------------------------------
    $modifiedJson = $updateJson -replace $findPattern, $replacement

    # -- 3e. Write to a temp file and post the update ----------------------------
    #
    # UpdateDashboard.ps1 expects a file path, so we save the JSON to a
    # temporary file and remove it once the update has been posted.
    $tempFile = [System.IO.Path]::GetTempFileName()
    try {
        Set-Content -Path $tempFile -Value $modifiedJson -Encoding UTF8

        & "$scripts\Dashboards\UpdateDashboard.ps1" `
            -BaseUrl           $BaseUrl `
            -DataViewName      $DataViewName `
            -AccessToken       $token `
            -DashboardId       $dashboardId `
            -DashboardJsonPath $tempFile
    }
    finally {
        Remove-Item $tempFile -ErrorAction SilentlyContinue
    }

    Write-Host "  [$dashboardId] $title - updated." -ForegroundColor Green
    $modifiedCount++
}

# ---------------------------------------------------------------------------
# Summary
# ---------------------------------------------------------------------------
Write-Host ""
Write-Host "Done. $modifiedCount dashboard(s) updated, $skippedCount skipped." -ForegroundColor Cyan

Back to the cookbook