#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"