Tutorial
Fill SharePoint metadata from file names with PowerShell
Turn file names into SharePoint columns (date, type, language, reference) with a rule-based PnP PowerShell script that adapts to any naming convention.
Thousands of documents land in SharePoint after a migration. The columns are empty, but the information is there, in the file names: 2026-02-10_INV_PRJ-1234_Supplier_EN.pdf holds a date, a document type, a project number and a language. Here is a PnP PowerShell script that turns those names into metadata, following rules you write yourself: it adapts to your naming convention, whatever it is, and touches neither "Modified", "Modified By" nor the version history.
Why move from names to metadata
A file name is information you cannot filter, sort or group by. A column can:
- a Date column gives you a "2025 documents" view, a reliable sort even when the file was edited since, and retention rules based on the document date;
- a "Document type" Choice column gives you a view per type (invoices, contracts, minutes) and a refiner in search;
- a managed metadata column (language, department, country) guarantees everyone uses the same values;
- a "Reference" Text column lets you find every document of a project or case in one search.
The name is still useful, but it is no longer the only source of truth.
Three rule types, for every naming convention
The script doesn't know your convention: you describe it, at the top of the script, in a RULES TO ADAPT section. Each rule reads one piece of information from the name and writes it to a column. There are three rule types.
Date: a date in the name
# A date at the start of the name: 2026-03-15, 2026.03.15, 20260315, 26.03.15 or 26-03-15
@{ Type = "Date"; Column = "DocumentDate" }
# A date elsewhere or in another order: describe where the day (d), month (m) and year (y) are
# Example for "Report_03-15-2026.pdf"
@{ Type = "Date"; Column = "DocumentDate"; Pattern = '(?<m>\d{2})-(?<d>\d{2})-(?<y>\d{4})' }
An impossible date (month 13, April 31) is ignored, never written.
Lookup: a code that becomes a value
A short code in the name (INV, HR, EN…) is translated into a readable value:
# Choice or Text column: the value is the text
@{ Type = "Lookup"; Column = "DocumentType"; Values = @{
INV = "Invoice"
MIN = "Minutes"
CTR = "Contract"
} }
# Managed metadata column: the value is the term path "Group|Term set|Term"
@{ Type = "Lookup"; Column = "Language"; Values = @{
EN = "My company|Languages|English"
FR = "My company|Languages|French"
} }
The code must be set apart by a separator (_, -, . or a space): EN is found in Report_EN.pdf, not in Agenda.pdf. And if a name contains two codes of the same rule (Contract_CTR-INV.pdf), the script doesn't pick one at random: it leaves the column empty and flags it.
Extract: a piece of the name copied as is
For a reference, a project, case or invoice number, described by a regular expression:
# PRJ- followed by 4 digits: "PRJ-1234"
@{ Type = "Extract"; Column = "Reference"; Pattern = 'PRJ-\d{4}' }
# Only the number, without the prefix: "INV-00042" gives "00042"
@{ Type = "Extract"; Column = "InvoiceNumber"; Pattern = 'INV-(?<value>\d+)' }
Examples for every department
A few common conventions, to copy into the rules section:
| Department | Example name | Rules |
|---|---|---|
| Accounting | 2026-02-10_INV_INV-00042_Smith.pdf | Date, Lookup type (INV, CN, QUO), Extract invoice number |
| HR | CTR_2025-09-01_Martin.pdf | Lookup type (CTR, AMD, INT), Date with Pattern since it isn't at the start |
| Projects | PRJ-1234_MIN_2026-05-20.docx | Extract project, Lookup type (MIN, SPEC, ACC), Date with Pattern |
| Communications | 26.03.15_PressRelease_EN.pdf | Date, Lookup language as managed metadata |
| Legal | 2024_CTR_ClientX_v3.pdf | Lookup type, Extract year if you don't have the full date |
Prerequisites
- PowerShell 7.4 or later, the PnP.PowerShell module and your own Entra ID application: the setup is in the article on bulk-restoring the recycle bin;
- the columns already created in the library, with their internal name. To find it: Library settings, click the column, it shows at the end of the URL (
Field=DocumentDate); - for managed metadata, the term store with your terms, and their
Group|Term set|Termpath.
What the script does
- It checks that every rule column exists before starting, and stops with a clear message otherwise.
- For each file in the library, or in a single folder, it applies every rule.
- It only fills a column when its value changes, using
SystemUpdate: no new version, "Modified" and "Modified By" unchanged. - It produces a report: what it read in each name, the columns written, and the "Ambiguous" or "Nothing found" cases.
Without -Apply, nothing is written: this is the dry run. And a second run rewrites nothing: everything comes out "Up to date".
I tested it with PowerShell 7.6 and PnP.PowerShell 3.4.1 on a test library: a Date column, a Choice column, a Text column and a managed metadata column, with dates in several formats, an impossible date, words that contain codes, ambiguous names, and a full second run. The files stayed at version 1.0.
The full script
Copy it into a Set-MetadataFromFileName.ps1 file, or download it directly. Adapt the RULES TO ADAPT section, the rest stays as is.
#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 = '(?<m>\d{2})-(?<d>\d{2})-(?<y>\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 {
@(
'^(?<y>\d{4})[-.](?<m>\d{2})[-.](?<d>\d{2})',
'^(?<y>\d{4})(?<m>\d{2})(?<d>\d{2})(?!\d)',
'^(?<y>\d{2})[-.](?<m>\d{2})[-.](?<d>\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"
Run it
# 1. Dry run on one folder, after adapting the rules
.\Set-MetadataFromFileName.ps1 -SiteUrl "https://contoso.sharepoint.com/sites/Finance" `
-ClientId "00000000-0000-0000-0000-000000000000" -Library "Documents" `
-FolderServerRelativeUrl "/sites/Finance/Shared Documents/Invoices"
# 2. Apply, after reviewing the report: same parameters, plus -Apply
The Metadata-….csv report lands in your Documents folder.
Pitfalls to know about
SystemUpdatedoes not trigger Power Automate. That is intended: you don't want a thousand documents to restart a thousand approval flows. But if a flow has to react to a column, you will need to start it another way.- A "contains" search gives false positives. Looking for "INV" anywhere in the name tags "Inventory_2025.pdf" as an invoice… and "Invitation_gala.pdf" too. The script requires the code to be set apart by a separator.
- Ambiguous names. With two codes of the same rule in one name, taking "the first one found" amounts to picking at random. The script prefers to write nothing for that column, while still filling the others.
- Dates and time zones. A Date column is stored in UTC. The script compares dates to the day so it doesn't rewrite an identical date shifted by a few hours. After a first run, still check one date in the interface.
- Choices must exist. For a Choice column, the value written must be one of the column's choices, exactly.
- Large libraries. The script reads items in pages of 2,000 and processes one file at a time. On tens of thousands of files, limit it to one folder with
-FolderServerRelativeUrland run it folder by folder.
What I recommend you do
- Look at your file names before migrating: if they follow a convention, they are a free source of metadata.
- Write your rules and test them on a single folder, as a dry run.
- Read the "Nothing found" and "Ambiguous" lines of the report: they show where the convention was not followed.
- Apply folder by folder on large libraries.
- Then make the columns required for new documents, so you don't have to do it again.
Document management and file plans are part of the training I run for administrators, Run SharePoint at tenant scale. And if you are preparing a migration or want to structure your documents, that is the kind of project I support through consulting. Once documents are classified, the next step is often to protect the most sensitive ones: see the secure copy of contracts to an archive site, a Power Automate flow I built on a demo tenant.
- SharePoint
- PowerShell
- PnP PowerShell
- Metadata
- Document management
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…