SharePoint Online: Rename Files in Document Library using PowerShell

Requirement: Rename files in SharePoint document library using PowerShell.

sharepoint online rename file in document library

How to rename a document in SharePoint Online?

Renaming a file in the SharePoint Online document library is pretty straightforward. The quickest way to rename a document is:

  • Right-click on your desired File and select Choose the Rename option.
    sharepoint online rename file
  • You can also rename a document in SharePoint by selecting the file >> Click on three little dots in the toolbar and then click on the “Rename” button. Provide a new name to the file in the Rename pop-up and click Save. Pretty simple right?
    rename file sharepoint online

SharePoint Online also provides rename options through the properties pane and by opening the file in Office web apps!

PowerShell CSOM Script to rename a file in SharePoint Online:

While renaming files in SharePoint Online is a fairly simple process, it can be tedious, especially if you’re trying to rename a lot of them. By using PowerShell, it’s super easy to rename files on SharePoint Online!

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL, Old File Name and New File Name
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$OldFileURL="/sites/Sales/Documents/Legal.docx"
$NewFileURL="/sites/Sales/Documents/LegalTemplate.docx"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Rename the File
    $File = $Ctx.Web.GetFileByServerRelativeUrl($OldFileURL) 
    $File.MoveTo($NewFileURL, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite) 
    $Ctx.ExecuteQuery()

    write-host -f Green "File Renamed successfully!"
}
Catch {
    write-host -f Red "Error Renaming File!" $_.Exception.Message
}

This script renames the given document to a new name. How about renaming all files from a SharePoint Online document library?

SharePoint Online rename files in bulk using PowerShell:

Say in SharePoint Online, you want to rename all documents that have a specific string in their names. 

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Set Variables for Site URL, Library Name and Item ID
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$LibraryName="Documents"
$OldString="National"
$NewString="Crescent"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Get the web and Library
    $Web=$Ctx.Web
    $List=$web.Lists.GetByTitle($LibraryName)

    #Get all items
    $Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
    $ListItems = $List.GetItems($Query)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()

    #Rename each file matching given old string
    Foreach($Item in $ListItems)
    {
        #Replace string in the File Name
        if($Item["FileRef"].ToString().Contains($OldString))
        {
            $CurrentURL=$Item["FileRef"].ToString()
            $NewURL = $CurrentURL.Replace($OldString,$NewString) 
            $Item.File.MoveTo($NewURL, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite) 
            $ctx.ExecuteQuery()
            Write-host -f Green "Renamed: "$CurrentURL
        }
    }
}
Catch {
    write-host -f Red "Error Renaming File!" $_.Exception.Message
} 

SharePoint Online: Rename a File using PnP PowerShell

To rename a file in SharePoint Online, use Rename-PnPFile cmdlet.

#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$FileURL= "Shared Documents/Active/Office 365 Proposal.pdf"
$NewFileName ="Office 365 Proposal V2.pdf"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Rename the File
Rename-PnPFile -SiteRelativeUrl $FileURL -TargetFileName $NewFileName -Force

Use the “-OverwriteIfAlreadyExists” switch to perform rename and replace the original file if exists! Also, you can use the “-ServerRelativeUrl” parameter to provide a server relative URL of the source file. Similarly, we can rename all files in a document library  using PnP PowerShell, as:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName = "Documents"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get All Files from the document library
$Files = Get-PnPListItem -List $LibraryName -PageSize 1000 | Where {$_["FileLeafRef"] -like "*.*"}
 
#Loop through each File
Write-host -f Green "Number of Files Found:"$Files.Count
ForEach($File in $Files)
{  
    Write-Host ("Renaming File '{0}' at {1}" -f $File["FileLeafRef"], $File["FileRef"])
    #Rename File
    Rename-PnPFile -ServerRelativeUrl $File["FileRef"] -TargetFileName "Old_$($File['FileLeafRef'])" -OverwriteIfAlreadyExists -Force
}

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

2 thoughts on “SharePoint Online: Rename Files in Document Library using PowerShell

  • If I do the rename in any of these options, will the link changed?

    Reply
    • In Modern SharePoint Online sites, If you rename a file, All links in Quick launch/top navigation/Web parts like Quick links get updated automatically!

      Reply

Leave a Reply