ShareFlow
All articles

Tutorial

SharePoint column formatting JSON with PowerShell

Status pills, icons, progress bars, overdue dates: 5 tested SharePoint column formatting JSON samples, plus a PnP PowerShell script to apply them everywhere.

Valentin Laurent17 min read
Share

SharePoint column formatting turns a status into a colored pill, a percentage into a progress bar, or an overdue date into a red warning, with a few lines of JSON. But you set it column by column, library by library: across twenty sites, that is a day of clicking, and JSON files that slowly drift apart. Here are five tested column formatting JSON samples, and a PnP PowerShell script that creates the column and applies its formatting to every library of several sites, with a dry run and a report.

What the script does

For each site, then each visible document library (technical libraries such as "Site Pages" or "Site Assets" are excluded), it can do three things, together or separately:

  1. Add a column if it is missing (Yes/No, choice, text, number, date…), add it to the default view and set its default value.
  2. Apply a JSON formatting to that column: pills, icons, progress bar, button.
  3. Apply a JSON formatting to the default view: view, row or command bar formatting.

Without -Apply, it changes nothing and exports what it would do. With -Apply, it applies, then reads every formatting back to check that it was actually saved. A second run redoes nothing: it reports "Already there" or "Already applied".

I tested it with PowerShell 7.6 and PnP.PowerShell 3.4.1, on two sites of a demo tenant, one of them a Microsoft 365 team site: four columns created with their formatting, a library filled with sample documents, then a second run that redid nothing.

SharePoint document library without formatting: the status, approval, progress and due date columns show plain text, check marks, numbers and dates
Before: raw values, no formatting
The same library after the script: statuses as colored pills, approval icons, progress bars, overdue dates highlighted in red
After: the four formattings applied by the script

Prerequisites

  • PowerShell 7.4 or later and the PnP.PowerShell module;
  • your own Entra ID application for PnP PowerShell, mandatory since September 2024;
  • an account that owns the sites, or is admin of their site collections.

The step-by-step setup is in the article on bulk-restoring the recycle bin.

Where column formatting lives

In a library, click the column header, then Column settings > Format this column. The panel offers a design mode (colors by value, no code) and an advanced mode where you paste the JSON.

Header menu of the status column, open on Column settings, with the Format this column option
Column settings > Format this column

The script writes exactly what this panel saves: the column's CustomFormatter property. After it runs, the panel opens straight in advanced mode, showing the JSON from your file.

Format column panel, column formatting tab in advanced mode: the editor shows the JSON applied by the script, with the Switch to design mode link
The JSON applied by the script, shown in advanced mode

One key difference with view formatting: column formatting applies in every view of the library, including views created later. That is the right level for a status or a due date.

5 column formatting JSON samples

All of them were applied with the script and checked in the test library. @currentField is the value of the formatted column; [$InternalName] reads another column of the same row. Column names and choice values are the ones from my example: adapt them to yours.

1. Status as colored pills

For a Choice column (Draft, In review, Approved, Archived). The sp-css-backgroundColor-… classes are the ones SharePoint uses in its design mode, with the same colors.

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "children": [
    {
      "elmType": "span",
      "txtContent": "@currentField",
      "style": {
        "display": "=if(@currentField == '', 'none', 'inline-block')",
        "white-space": "nowrap",
        "padding": "2px 10px",
        "border-radius": "12px",
        "font-weight": "600"
      },
      "attributes": {
        "class": "=if(@currentField == 'Approved', 'sp-css-backgroundColor-BgMintGreen sp-css-color-MintGreenFont', if(@currentField == 'In review', 'sp-css-backgroundColor-BgGold sp-css-color-GoldFont', if(@currentField == 'Draft', 'sp-css-backgroundColor-BgCornflowerBlue sp-css-color-CornflowerBlueFont', 'sp-css-backgroundColor-BgLightGray sp-css-color-LightGrayFont')))"
      }
    }
  ]
}
Status column as pills: approved in green, archived in gray, draft in blue, in review in yellow
Statuses as pills

Download status-pills.json

2. An icon for a Yes/No column

For a Yes/No column. The value compares to true; the sp-field-severity--… classes color the cell (green, orange, red) and the icons come from Fluent UI.

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "style": { "display": "flex", "align-items": "center" },
  "attributes": {
    "class": "=if(@currentField == true, 'sp-field-severity--warning', 'sp-field-severity--good')"
  },
  "children": [
    {
      "elmType": "span",
      "style": { "padding": "0 6px" },
      "attributes": {
        "iconName": "=if(@currentField == true, 'Warning', 'CheckMark')"
      }
    },
    {
      "elmType": "span",
      "style": { "padding-right": "6px" },
      "txtContent": "=if(@currentField == true, 'To approve', 'Not required')"
    }
  ]
}
Approval column: green cells with a check mark when not required, orange cells with a warning triangle when approval is needed
A Yes/No column you can read at a glance

Download approval-icon.json

3. A progress bar for a percentage

For a Number column filled from 0 to 100. The bar turns green at 100%. If your column is set to "Show as percentage", SharePoint stores 0.6, not 60: multiply @currentField by 100 in both formulas.

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "style": {
    "display": "=if(toString(@currentField) == '', 'none', 'flex')",
    "align-items": "center",
    "width": "100%"
  },
  "children": [
    {
      "elmType": "div",
      "style": {
        "flex-grow": "1",
        "height": "8px",
        "margin-right": "8px",
        "border-radius": "4px",
        "overflow": "hidden",
        "background-color": "#edebe9"
      },
      "children": [
        {
          "elmType": "div",
          "style": {
            "height": "100%",
            "width": "=if(@currentField > 100, '100%', @currentField + '%')",
            "background-color": "=if(@currentField >= 100, '#107c10', '#0078d4')"
          }
        }
      ]
    },
    {
      "elmType": "span",
      "style": { "min-width": "40px", "text-align": "right" },
      "txtContent": "=@currentField + ' %'"
    }
  ]
}
Progress column as bars: two full green bars at 100%, blue bars at 10, 60, 80 and 30%
Progress as a bar

Download progress-bar.json

4. A due date in red once it has passed

For a Date column. @now is today's date, and dates compare in milliseconds: 604800000 is 7 days. Red if the date has passed, orange if it falls within the week, and nothing if the document is already approved: that is what [$ReviewStatus] is for, it reads the neighboring column.

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "style": {
    "display": "=if(toString(@currentField) == '', 'none', 'flex')",
    "align-items": "center"
  },
  "attributes": {
    "class": "=if([$ReviewStatus] == 'Approved', '', if(@currentField < @now, 'sp-field-severity--blocked', if(@currentField <= @now + 604800000, 'sp-field-severity--warning', '')))"
  },
  "children": [
    {
      "elmType": "span",
      "style": { "padding": "0 6px" },
      "attributes": {
        "iconName": "=if([$ReviewStatus] == 'Approved', 'CheckMark', if(@currentField < @now, 'Error', if(@currentField <= @now + 604800000, 'Clock', 'Calendar')))"
      }
    },
    {
      "elmType": "span",
      "style": { "padding-right": "6px", "white-space": "nowrap" },
      "txtContent": "=toLocaleDateString(@currentField) + if([$ReviewStatus] != 'Approved' && @currentField < @now, ' (overdue)', '')"
    }
  ]
}
Status and due date columns: two overdue dates in red, a date within the week in orange with a clock, the date of an approved document with no warning
Overdue dates stand out, except for approved documents

Download due-date-overdue.json

5. A button that moves the status forward

The pill from sample 1, plus an Approve button shown only for documents "In review". The setValue action updates the ReviewStatus column in one click, without Power Automate. The user needs permission to edit the item.

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "style": { "display": "flex", "align-items": "center" },
  "children": [
    {
      "elmType": "span",
      "txtContent": "@currentField",
      "style": {
        "display": "=if(@currentField == '', 'none', 'inline-block')",
        "white-space": "nowrap",
        "padding": "2px 10px",
        "border-radius": "12px",
        "font-weight": "600"
      },
      "attributes": {
        "class": "=if(@currentField == 'Approved', 'sp-css-backgroundColor-BgMintGreen sp-css-color-MintGreenFont', if(@currentField == 'In review', 'sp-css-backgroundColor-BgGold sp-css-color-GoldFont', if(@currentField == 'Draft', 'sp-css-backgroundColor-BgCornflowerBlue sp-css-color-CornflowerBlueFont', 'sp-css-backgroundColor-BgLightGray sp-css-color-LightGrayFont')))"
      }
    },
    {
      "elmType": "button",
      "txtContent": "Approve",
      "customRowAction": {
        "action": "setValue",
        "actionInput": { "ReviewStatus": "Approved" }
      },
      "attributes": {
        "class": "ms-fontColor-themePrimary ms-bgColor-themeLighter--hover"
      },
      "style": {
        "display": "=if(@currentField == 'In review', 'inline-flex', 'none')",
        "white-space": "nowrap",
        "margin-left": "8px",
        "padding": "2px 8px",
        "border": "1px solid",
        "border-radius": "4px",
        "background-color": "transparent",
        "cursor": "pointer"
      }
    }
  ]
}
Status column with an approve button next to the two in-review pills
One click on the button marks the document as approved

Download status-approve-button.json

Bonus: hide "Add shortcut to OneDrive" and "Sync"

The same script also applies a view formatting, with -ViewFormatterPath. Command bar formatting, for instance, lets you hide, rename or move the buttons of a library. This JSON hides the two commands that expose the library in OneDrive:

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/row-formatting.schema.json",
  "commandBarProps": {
    "commands": [
      { "key": "addShortcutToOneDriveCommand", "hide": true },
      { "key": "syncCommand", "hide": true }
    ]
  }
}

Download hide-shortcut-and-sync.json. To understand what these two buttons do, see the article on OneDrive sync for SharePoint libraries.

The full script

Copy it into a Set-LibrariesBulk-en.ps1 file, or download it directly.

#Requires -Version 7.4
#Requires -Modules PnP.PowerShell

<#
.SYNOPSIS
    Applies the same configuration to every document library of several
    SharePoint sites: a column with its default value, a JSON column
    formatting, and/or a JSON formatting of the default view.

.DESCRIPTION
    For each site, then each visible library (system libraries excluded):
      1. if a column is requested: creates it if missing, then sets its
         default value;
      2. if -ColumnFormatterPath is given: applies that JSON as the column
         formatting (pills, icons, progress bar…);
      3. if -ViewFormatterPath is given: applies that JSON as the formatting of
         the default view (view, row or command bar formatting).
    The script is idempotent: what is already in place is reported, not redone.
    Every formatting written is read back to check that it was saved.

    Without -Apply, it changes nothing: it exports the plan to a CSV (dry run).

.PARAMETER Sites
    URLs of the sites to process.

.PARAMETER ClientId
    ID of the Entra ID application used by PnP.PowerShell.

.PARAMETER Libraries
    Optional: titles of the libraries to process. Default: all of them.

.PARAMETER ColumnDisplayName
    Display name of the column to add.

.PARAMETER ColumnInternalName
    Internal name (no spaces or accents). It is the one used in filters, JSON
    and Power Automate: choose it carefully, it never changes afterwards.
    A column that already exists (even one created by hand) is reused.

.PARAMETER ColumnType
    Boolean (Yes/No), Text, Note, Number, DateTime or Choice. Boolean by default.

.PARAMETER Choices
    Allowed values, for a Choice column.

.PARAMETER DefaultValue
    Default value. For a Yes/No column: 1 (Yes) or 0 (No).

.PARAMETER ColumnFormatterPath
    JSON formatting file to apply to the -ColumnInternalName column.

.PARAMETER ViewFormatterPath
    JSON formatting file to apply to the default view.

.PARAMETER Apply
    Actually applies the changes. Without this switch: dry run.

.PARAMETER ReportFolder
    Folder for the CSV reports. Default: your Documents folder.

.EXAMPLE
    # Dry run: a Yes/No column "Approval required" (No by default) on two sites
    .\Set-LibrariesBulk-en.ps1 -Sites "https://contoso.sharepoint.com/sites/Finance","https://contoso.sharepoint.com/sites/HR" `
        -ClientId "00000000-0000-0000-0000-000000000000" `
        -ColumnDisplayName "Approval required" -ColumnInternalName "ApprovalRequired" -DefaultValue 0

.EXAMPLE
    # A "Review status" choice column with its colored pills, on every library
    .\Set-LibrariesBulk-en.ps1 -Sites (Get-Content .\sites.txt) -ClientId "00000000-0000-0000-0000-000000000000" `
        -ColumnDisplayName "Review status" -ColumnInternalName "ReviewStatus" -ColumnType Choice `
        -Choices "Draft","In review","Approved","Archived" -DefaultValue "Draft" `
        -ColumnFormatterPath ".\status-pills.json" -Apply

.EXAMPLE
    # Command bar formatting on every library
    .\Set-LibrariesBulk-en.ps1 -Sites (Get-Content .\sites.txt) -ClientId "00000000-0000-0000-0000-000000000000" `
        -ViewFormatterPath ".\hide-shortcut-and-sync.json" -Apply
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory)] [string[]] $Sites,
    [Parameter(Mandatory)] [string]   $ClientId,
    [string[]] $Libraries,
    [string]   $ColumnDisplayName,
    [string]   $ColumnInternalName,
    [ValidateSet("Boolean", "Text", "Note", "Number", "DateTime", "Choice")] [string] $ColumnType = "Boolean",
    [string[]] $Choices,
    [string]   $DefaultValue,
    [string]   $ColumnFormatterPath,
    [string]   $ViewFormatterPath,
    [switch]   $Apply,
    [string]   $ReportFolder = (Join-Path $HOME "Documents")
)

$ErrorActionPreference = "Stop"
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"

# --------------------------------------------------------------------------
# 1. Checks before starting
# --------------------------------------------------------------------------
$doColumn     = [bool] $ColumnInternalName
$doColumnJson = [bool] $ColumnFormatterPath
$doViewJson   = [bool] $ViewFormatterPath
if (-not $doColumn -and -not $doViewJson) {
    throw "Nothing to do: give a column (-ColumnInternalName) and/or a view JSON file (-ViewFormatterPath)."
}
if ($doColumnJson -and -not $doColumn) {
    throw "-ColumnFormatterPath applies to a column: also give -ColumnInternalName."
}
if ($doColumn -and -not $ColumnDisplayName) { $ColumnDisplayName = $ColumnInternalName }
if ($doColumn -and $ColumnInternalName -notmatch '^[A-Za-z][A-Za-z0-9_]*$') {
    throw "Invalid internal name: letters, digits and _ only, starting with a letter."
}
if ($ColumnType -eq "Choice" -and -not $Choices) {
    throw "A Choice column needs its values: -Choices."
}

# The JSON files are read and validated once: a syntax error stops everything
# before the first site is touched.
function Read-Formatter([string] $Path) {
    # [IO.File]::ReadAllText, not Get-Content -Raw: Get-Content returns a string
    # "decorated" by PowerShell that PnP rejects with a mere warning.
    $json = [IO.File]::ReadAllText((Resolve-Path $Path))
    try { $null = $json | ConvertFrom-Json } catch { throw "Invalid JSON ($Path): $($_.Exception.Message)" }
    return $json
}
$columnFormatter = if ($doColumnJson) { Read-Formatter $ColumnFormatterPath }
$viewFormatter   = if ($doViewJson)   { Read-Formatter $ViewFormatterPath }

# Technical libraries never to touch, matched by URL rather than by title,
# which changes with the site language.
$excludedUrls = @("FormServerTemplates", "SiteAssets", "Style Library", "SitePages",
                  "Pages", "PublishingImages", "IWConvertedForms", "Teams Wiki Data")

$report = [System.Collections.Generic.List[object]]::new()
function Add-Report($Site, $Library, $Action, $Status, $Message = "") {
    $report.Add([pscustomobject]@{
        Site = $Site; Library = $Library; Action = $Action; Status = $Status; Message = $Message })
}

# --------------------------------------------------------------------------
# 2. Process each site
# --------------------------------------------------------------------------
foreach ($site in $Sites) {
    Write-Host ""
    Write-Host "=== $site" -ForegroundColor Cyan
    try {
        Connect-PnPOnline -Url $site -Interactive -ClientId $ClientId
    }
    catch {
        Write-Warning "Cannot connect: $($_.Exception.Message)"
        Add-Report $site "" "Connect" "Error" $_.Exception.Message
        continue
    }

    # Visible document libraries (template 101), system libraries excluded.
    $libs = @(Get-PnPList -Includes RootFolder.Name, IsSystemList, IsCatalog | Where-Object {
        $_.BaseTemplate -eq 101 -and -not $_.Hidden -and -not $_.IsSystemList -and -not $_.IsCatalog -and
        $_.RootFolder.Name -notin $excludedUrls -and
        (-not $Libraries -or $_.Title -in $Libraries)
    })
    Write-Host "$($libs.Count) library(ies) to process."

    foreach ($lib in $libs) {
        Write-Host "  - $($lib.Title)"

        # 2.1 The column
        $field = $null
        if ($doColumn) {
            try {
                $field = Get-PnPField -List $lib -Identity $ColumnInternalName -Includes CustomFormatter, DefaultValue -ErrorAction SilentlyContinue
                if (-not $field) {
                    if ($Apply) {
                        $fieldArgs = @{ List = $lib; DisplayName = $ColumnDisplayName; InternalName = $ColumnInternalName
                                        Type = $ColumnType; AddToDefaultView = $true }
                        if ($ColumnType -eq "Choice") { $fieldArgs.Choices = $Choices }
                        $null = Add-PnPField @fieldArgs
                        $field = Get-PnPField -List $lib -Identity $ColumnInternalName -Includes CustomFormatter, DefaultValue
                        Add-Report $site $lib.Title "Column created" "OK"
                    } else {
                        Add-Report $site $lib.Title "Column to create" "Planned"
                    }
                } else {
                    Add-Report $site $lib.Title "Column" "Already there"
                }

                # Default value, only if it differs from the current one.
                if ($PSBoundParameters.ContainsKey("DefaultValue")) {
                    if (-not $field) {
                        Add-Report $site $lib.Title "Default value = $DefaultValue" "Planned"
                    } elseif ($field.DefaultValue -eq $DefaultValue) {
                        Add-Report $site $lib.Title "Default value" "Already $DefaultValue"
                    } elseif ($Apply) {
                        Set-PnPField -List $lib -Identity $ColumnInternalName -Values @{ DefaultValue = $DefaultValue } | Out-Null
                        Add-Report $site $lib.Title "Default value = $DefaultValue" "OK"
                    } else {
                        Add-Report $site $lib.Title "Default value = $DefaultValue" "Planned"
                    }
                }
            }
            catch { Add-Report $site $lib.Title "Column" "Error" $_.Exception.Message }
        }

        # 2.2 The column formatting
        if ($doColumnJson) {
            try {
                if (-not $field) {
                    # Column not created yet (dry run) or failed just before.
                    Add-Report $site $lib.Title "Column formatting" $(if ($Apply) { "Error" } else { "Planned" })
                }
                elseif ($field.CustomFormatter -eq $columnFormatter) {
                    Add-Report $site $lib.Title "Column formatting" "Already applied"
                }
                elseif ($Apply) {
                    Set-PnPField -List $lib -Identity $ColumnInternalName -Values @{ CustomFormatter = $columnFormatter } | Out-Null
                    $check = Get-PnPField -List $lib -Identity $ColumnInternalName -Includes CustomFormatter
                    if ($check.CustomFormatter -eq $columnFormatter) {
                        Add-Report $site $lib.Title "Column formatting" "OK" `
                            $(if ($field.CustomFormatter) { "Previous formatting replaced." } else { "" })
                    } else {
                        Add-Report $site $lib.Title "Column formatting" "Error" "The formatting was not saved."
                    }
                }
                else {
                    Add-Report $site $lib.Title "Column formatting" "Planned" `
                        $(if ($field.CustomFormatter) { "Would replace an existing formatting." } else { "" })
                }
            }
            catch { Add-Report $site $lib.Title "Column formatting" "Error" $_.Exception.Message }
        }

        # 2.3 The default view formatting
        if ($doViewJson) {
            try {
                $view = Get-PnPView -List $lib -Includes CustomFormatter | Where-Object DefaultView | Select-Object -First 1
                if (-not $view) {
                    Add-Report $site $lib.Title "View formatting" "Error" "No default view."
                }
                elseif ($view.CustomFormatter -eq $viewFormatter) {
                    Add-Report $site $lib.Title "View formatting ($($view.Title))" "Already applied"
                }
                elseif ($Apply) {
                    # Warning: replaces any existing formatting of this view.
                    Set-PnPView -List $lib -Identity $view.Id -Values @{ CustomFormatter = $viewFormatter } | Out-Null

                    # Read the view back: when something goes wrong, Set-PnPView may
                    # only print a warning and save nothing.
                    $check = Get-PnPView -List $lib -Identity $view.Id -Includes CustomFormatter
                    if ($check.CustomFormatter -eq $viewFormatter) {
                        Add-Report $site $lib.Title "View formatting ($($view.Title))" "OK" `
                            $(if ($view.CustomFormatter) { "Previous formatting replaced." } else { "" })
                    } else {
                        Add-Report $site $lib.Title "View formatting ($($view.Title))" "Error" "The formatting was not saved."
                    }
                }
                else {
                    Add-Report $site $lib.Title "View formatting ($($view.Title))" "Planned" `
                        $(if ($view.CustomFormatter) { "Would replace an existing formatting." } else { "" })
                }
            }
            catch { Add-Report $site $lib.Title "View formatting" "Error" $_.Exception.Message }
        }
    }
}

# --------------------------------------------------------------------------
# 3. Report
# --------------------------------------------------------------------------
if (-not (Test-Path $ReportFolder)) { New-Item -ItemType Directory -Path $ReportFolder | Out-Null }
$mode = if ($Apply) { "apply" } else { "dryrun" }
$reportPath = Join-Path $ReportFolder "Libraries-$mode-$stamp.csv"
$report | Export-Csv -Path $reportPath -NoTypeInformation -Encoding UTF8 -Delimiter ";"

Write-Host ""
$report | Format-Table Library, Action, Status -GroupBy Site -AutoSize | Out-Host
if (-not $Apply) { Write-Host "Dry run: nothing was changed. Run again with -Apply once you have checked the report." -ForegroundColor Yellow }
$errors = @($report | Where-Object Status -eq "Error").Count
Write-Host ("Done. {0} line(s) in the report, {1} error(s)." -f $report.Count, $errors) `
    -ForegroundColor $(if ($errors) { "Yellow" } else { "Green" })
Write-Host "Report: $reportPath"

Run it

A "Review status" choice column with its pills, on two sites, as a dry run first (without -Apply):

$sites = "https://contoso.sharepoint.com/sites/Finance", "https://contoso.sharepoint.com/sites/HR"
$clientId = "00000000-0000-0000-0000-000000000000"

.\Set-LibrariesBulk-en.ps1 -Sites $sites -ClientId $clientId `
    -ColumnDisplayName "Review status" -ColumnInternalName "ReviewStatus" -ColumnType Choice `
    -Choices "Draft", "In review", "Approved", "Archived" -DefaultValue "Draft" `
    -ColumnFormatterPath ".\status-pills.json"

Read the CSV report, then run the same command again with -Apply. Here is a second run on my two test sites: on the first one, I had removed the formatting by hand, and the script puts it back; on the second one, everything was already in place, and it touches nothing.

PowerShell 7 console: the script processes the Document tracking library of two sites; on the first, the column formatting is applied (OK); on the second, everything is reported as Already there, Already Draft and Already applied; 0 errors
A second run: only what is missing gets applied

A Yes/No "Approval required" column, "No" by default, with its icon:

.\Set-LibrariesBulk-en.ps1 -Sites $sites -ClientId $clientId `
    -ColumnDisplayName "Approval required" -ColumnInternalName "ApprovalRequired" -DefaultValue 0 `
    -ColumnFormatterPath ".\approval-icon.json" -Apply

A column that already exists: give only its internal name and the JSON. The script reuses it without recreating it.

.\Set-LibrariesBulk-en.ps1 -Sites (Get-Content .\sites.txt) -ClientId $clientId `
    -ColumnInternalName "DueDate" -ColumnFormatterPath ".\due-date-overdue.json" -Apply

The command bar formatting, on a list of sites kept in a text file (one URL per line):

.\Set-LibrariesBulk-en.ps1 -Sites (Get-Content .\sites.txt) -ClientId $clientId `
    -ViewFormatterPath ".\hide-shortcut-and-sync.json" -Apply

To process only some libraries, add -Libraries "Documents", "Archives".

Pitfalls to know about

  • Get-Content -Raw makes the formatting fail silently. PowerShell returns a "decorated" string that PnP rejects with a mere warning: the view stays unchanged, and a naive script prints "OK". The script therefore reads the files with [IO.File]::ReadAllText, then reads every formatting back to confirm it was saved.
  • -Includes only loads what you ask for. My test showed it: with Get-PnPField -Includes CustomFormatter, the DefaultValue property came back empty, and the script rewrote the default value on every run. It now asks for both properties.
  • Library titles change with the language. On a French site, "Style Library" is called "Bibliothèque de styles". Excluding technical libraries by their English title lets them through: the script spots them by URL and by the IsSystemList and IsCatalog properties.
  • The JSON depends on internal names and choice values. [$ReviewStatus] and 'In review' are hard-coded. Rename a choice, and the pill turns gray with no error message. Keep the values in your file plan, and the JSON with them.
  • "Switch to design mode" wipes the JSON. The panel says so in small print: a site owner who switches to design mode loses the formatting. Run the script again to restore it.
  • An existing formatting gets replaced. If the column or view already had a JSON, it is overwritten. The dry run flags it ("Would replace an existing formatting"): check before applying.
  • The default value only applies to new files. Existing documents keep an empty column. To fill them, see the script from the article on metadata from file names, which updates items in bulk with Set-PnPListItem.
  • Hiding a button is not a security measure. It is a UI convenience. To really prevent sync, you need an admin setting, for instance Set-SPOTenant -HideSyncButtonOnTeamSite $true, which hides the button across the tenant (without stopping syncs already in place).
  • The internal name is final. It is used in filters, JSON and Power Automate, and never changes after creation. No spaces or accents: ApprovalRequired, not Approval required.

What I recommend you do

  1. Define the column once (display name, internal name, type, values, default value) and write it into your file plan.
  2. Fine-tune the JSON on a test library, in the panel's advanced mode: the preview is immediate. Then save it to a file.
  3. Prefer a site column if it must be used in searches or cross-library views; this script creates one column per library, which is enough for a local need.
  4. Run the dry run on every site, read the report, then apply.
  5. Keep the site list and the JSON files in a versioned folder: the next column, or a JSON fix, will be one command away.

To go further with lists, the article Microsoft Lists: overview and practical examples covers design mode and advanced mode on concrete cases. Automation with PnP PowerShell is part of the training I run for administrators, Run SharePoint at tenant scale. And if you want to standardize the configuration of your sites, that is the kind of project I support through consulting.

Sources

Share this article

Know a colleague or client who deals with this? Send them the article in one click.

Read next

Comments

Loading comments…

Leave a comment

Comments are reviewed before they are published. Only your first name and last-name initial are shown.