#Requires -Version 7.4 #Requires -Modules PnP.PowerShell <# .SYNOPSIS Fills SharePoint columns from file names, using rules you describe yourself at the top of the script. .DESCRIPTION You describe RULES (the "RULES TO ADAPT" section below). Each rule reads one piece of information from the file name and writes it to a column: Date a date (at the start of the name by default, or wherever you say) Lookup a standalone code in the name (EN, INV, HR…) translated into a value (Choice, text or managed metadata term) Extract a piece of the name copied as is (reference, project number…) For each file, the script applies every rule and only updates the columns whose value changes, using SystemUpdate: "Modified", "Modified By" and the version history stay untouched. The flip side: Power Automate flows triggered by a modification do not run. Without -Apply, nothing is changed: the script exports what it would do (dry run). .PARAMETER SiteUrl Site URL. .PARAMETER ClientId ID of the Entra ID application used by PnP.PowerShell. .PARAMETER Library Library title. .PARAMETER FolderServerRelativeUrl Optional: limits processing to one folder, for example /sites/Finance/Shared Documents/Invoices .PARAMETER Apply Actually applies the changes. Without this switch: dry run. .PARAMETER ReportFolder Folder for the CSV reports. Default: your Documents folder. .EXAMPLE # 1. Adapt the RULES section, then run a dry run .\Set-MetadataFromFileName-en.ps1 -SiteUrl "https://contoso.sharepoint.com/sites/Finance" ` -ClientId "00000000-0000-0000-0000-000000000000" -Library "Documents" # 2. Review the report, then apply .\Set-MetadataFromFileName-en.ps1 -SiteUrl "https://contoso.sharepoint.com/sites/Finance" ` -ClientId "00000000-0000-0000-0000-000000000000" -Library "Documents" -Apply #> [CmdletBinding()] param( [Parameter(Mandatory)] [string] $SiteUrl, [Parameter(Mandatory)] [string] $ClientId, [Parameter(Mandatory)] [string] $Library, [string] $FolderServerRelativeUrl, [switch] $Apply, [string] $ReportFolder = (Join-Path $HOME "Documents") ) # ========================================================================== # RULES TO ADAPT # One @{ … } line per piece of information to extract. Delete the ones you # don't need, copy and paste to add more. "Column" is the column's INTERNAL # NAME (Column settings > end of the URL). # ========================================================================== $Rules = @( # --- Date -------------------------------------------------------------- # Without Pattern: a date at the START of the name, as 2026-03-15, # 2026.03.15, 20260315, 26.03.15 or 26-03-15. @{ Type = "Date"; Column = "DocumentDate" } # With Pattern: a date anywhere, in your own format. Name the parts # y (year, 2 or 4 digits), m (month) and d (day). Example for # "Report_03-15-2026.pdf" (month first): # @{ Type = "Date"; Column = "DocumentDate"; Pattern = '(?\d{2})-(?\d{2})-(?\d{4})' } # --- Lookup: a standalone code in the name -> a value -------------------- # The code must be set apart by _ - . or a space: "EN" is found in # "Report_EN.pdf", not in "Agenda.pdf". # For a managed metadata column, the value is the term path # "Group|Term set|Term" (or the term ID). @{ Type = "Lookup"; Column = "Language"; Values = @{ EN = "My company|Languages|English" FR = "My company|Languages|French" ES = "My company|Languages|Spanish" } } # For a Choice or Text column, the value is simply the text. @{ Type = "Lookup"; Column = "DocumentType"; Values = @{ INV = "Invoice" MIN = "Minutes" CTR = "Contract" } } # --- Extract: a piece of the name copied as is --------------------------- # Described by a regular expression. Here: PRJ- followed by 4 digits. @{ Type = "Extract"; Column = "Reference"; Pattern = 'PRJ-\d{4}' } ) # ========================================================================== $ErrorActionPreference = "Stop" $stamp = Get-Date -Format "yyyyMMdd-HHmmss" # -------------------------------------------------------------------------- # 1. Name-reading functions # -------------------------------------------------------------------------- # Builds a date from the y, m, d parts. $null if the date is impossible # (month 13, April 31…): the DateTime constructor rejects it. function New-SafeDate([string] $Y, [string] $M, [string] $D) { $year = [int]$Y if ($Y.Length -eq 2) { $year += 2000 } try { return [datetime]::new($year, [int]$M, [int]$D) } catch { return $null } } # Date rule: returns the date found, or $null. function Find-Date([string] $Name, $Rule) { $patterns = if ($Rule.Pattern) { @($Rule.Pattern) } else { @( '^(?\d{4})[-.](?\d{2})[-.](?\d{2})', '^(?\d{4})(?\d{2})(?\d{2})(?!\d)', '^(?\d{2})[-.](?\d{2})[-.](?\d{2})(?!\d)' ) } foreach ($p in $patterns) { if ($Name -match $p) { return New-SafeDate $Matches.y $Matches.m $Matches.d } } return $null } # Lookup rule: returns the codes found, set apart by a separator. # Several different codes = ambiguous name. function Find-Codes([string] $Name, [string[]] $Codes) { $base = [IO.Path]::GetFileNameWithoutExtension($Name) return @($Codes | Where-Object { $base -match "(?i)(^|[_\-.\s])$([regex]::Escape($_))($|[_\-.\s])" } | Sort-Object -Unique) } # Extract rule: returns the first matching piece (or the named group # "value" if there is one), or $null. function Find-Extract([string] $Name, $Rule) { $base = [IO.Path]::GetFileNameWithoutExtension($Name) if ($base -match $Rule.Pattern) { if ($Matches.ContainsKey("value")) { return $Matches.value } return $Matches[0] } return $null } # Is the column's current value already the one we want to write? function Test-SameValue($Current, $Wanted, [string] $FieldType) { if ($null -eq $Current -or "$Current" -eq "") { return $false } if ($FieldType -like "DateTime") { # Compare to the day: the column is stored in UTC. return ([datetime]$Current).ToLocalTime().Date -eq ([datetime]$Wanted).Date } if ($FieldType -like "TaxonomyField*") { $guid = [guid]::Empty if ([guid]::TryParse("$Wanted", [ref] $guid)) { return "$($Current.TermGuid)" -eq "$Wanted" } return $Current.Label -eq ("$Wanted" -split '\|')[-1] } return "$Current" -eq "$Wanted" } # -------------------------------------------------------------------------- # 2. Connect and check # -------------------------------------------------------------------------- Connect-PnPOnline -Url $SiteUrl -Interactive -ClientId $ClientId # Every rule column must exist: we also get its type. $fieldTypes = @{} foreach ($rule in $Rules) { if ($rule.Type -notin "Date", "Lookup", "Extract") { throw "Unknown rule type: $($rule.Type)" } $field = Get-PnPField -List $Library -Identity $rule.Column -ErrorAction SilentlyContinue if (-not $field) { throw "Column '$($rule.Column)' does not exist in '$Library' (check its internal name)." } $fieldTypes[$rule.Column] = $field.TypeAsString } $getParams = @{ List = $Library; PageSize = 2000 } if ($FolderServerRelativeUrl) { $getParams.FolderServerRelativeUrl = $FolderServerRelativeUrl } # FSObjType 0 = file (1 = folder). $files = @(Get-PnPListItem @getParams | Where-Object { $_.FieldValues["FSObjType"] -eq 0 }) Write-Host "$($files.Count) file(s) to analyse, $($Rules.Count) rule(s)." # -------------------------------------------------------------------------- # 3. Apply the rules to each file # -------------------------------------------------------------------------- $report = [System.Collections.Generic.List[object]]::new() $counters = [ordered]@{ "Updated" = 0; "Planned" = 0; "Up to date" = 0; "Ambiguous" = 0; "Nothing found" = 0; "Error" = 0 } foreach ($item in $files) { $name = $item.FieldValues["FileLeafRef"] $values = @{} # column -> new value $found = @() # what was read from the name, for the report $warnings = @() # ambiguities foreach ($rule in $Rules) { $col = $rule.Column $wanted = $null switch ($rule.Type) { "Date" { $wanted = Find-Date $name $rule if ($wanted) { $found += "$col=$($wanted.ToString('yyyy-MM-dd'))" } } "Lookup" { $codes = @(Find-Codes $name $rule.Values.Keys) if ($codes.Count -gt 1) { $warnings += "${col}: several codes ($($codes -join '+')), left empty" } elseif ($codes.Count -eq 1) { $wanted = $rule.Values[$codes[0]] $found += "$col=$($codes[0])" } } "Extract" { $wanted = Find-Extract $name $rule if ($wanted) { $found += "$col=$wanted" } } } if ($wanted -and -not (Test-SameValue $item.FieldValues[$col] $wanted $fieldTypes[$col])) { $values[$col] = $wanted } } $status = if ($values.Count -gt 0) { if ($Apply) { "Updated" } else { "Planned" } } elseif ($warnings.Count -gt 0) { "Ambiguous" } elseif ($found.Count -gt 0) { "Up to date" } else { "Nothing found" } $message = $warnings -join "; " if ($status -eq "Updated") { try { # SystemUpdate: no new version, "Modified / Modified By" unchanged. Set-PnPListItem -List $Library -Identity $item.Id -Values $values -UpdateType SystemUpdate | Out-Null } catch { $status = "Error" $message = $_.Exception.Message } } $counters[$status]++ $report.Add([pscustomobject]@{ File = $name; Found = ($found -join ", "); Columns = ($values.Keys -join ", ") Status = $status; Message = $message }) } # -------------------------------------------------------------------------- # 4. Report # -------------------------------------------------------------------------- if (-not (Test-Path $ReportFolder)) { New-Item -ItemType Directory -Path $ReportFolder | Out-Null } $mode = if ($Apply) { "apply" } else { "dryrun" } $reportPath = Join-Path $ReportFolder "Metadata-$mode-$stamp.csv" $report | Export-Csv -Path $reportPath -NoTypeInformation -Encoding UTF8 Write-Host "" $counters.GetEnumerator() | Where-Object Value | ForEach-Object { Write-Host ("{0,-13}: {1}" -f $_.Key, $_.Value) } if (-not $Apply) { Write-Host "Dry run: nothing was changed. Run again with -Apply after checking the report." -ForegroundColor Yellow } Write-Host "Report: $reportPath"