SharePoint Online: Rename Files in Document Library using PowerShell

Requirement: Rename files in the SharePoint document library using PowerShell.

sharepoint online rename file in document library

How to rename a document in SharePoint Online?

In SharePoint Online, you can rename files in the browser or with PowerShell. In this blog post, we will walk you through the process of renaming files in SharePoint Online. We will also demonstrate how to rename files in a document library using PowerShell, with some code examples that you can use as a reference.

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

  1. Navigate to the library where the file to rename is stored.
  2. Right-click on your desired File and Choose the “Rename” option. (Or Select the File >> Click on the “Rename” button in the Toolbar)
    sharepoint online rename file
  3. 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!

How to rename the file extension in SharePoint Online?
Use the “File Explorer View” to open the document library in Windows Explorer and Rename the File’s extension!

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

    #Copy and 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. Shall we update the “Title” field from the file name?

#Set Variables for Site URL, Old File Name and New File Name
$SiteURL= "https://crescent.sharepoint.com/sites/Retail"
$FileServerRelativeURL="/sites/Retail/Invoices/export%20user%20information.xlsx"
 
#Setup Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
 
    #Get the File
    $File = $Ctx.Web.GetFileByServerRelativeUrl($FileServerRelativeURL)
    $Ctx.Load($File)
    $Ctx.ExecuteQuery()

    #Set Title Field Value of the File
    $ListItem = $File.ListItemAllFields
    $Listitem["Title"] = $File.Name
    $ListItem.Update()
    $Ctx.ExecuteQuery()
 
    write-host -f Green "File Title Updated successfully!"
}
Catch {
    write-host -f Red "Error Updating File Title!" $_.Exception.Message
}

More on updating document metadata is here: SharePoint Online: How to update document properties using PowerShell?

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 the Rename-PnPFile cmdlet.

#Config Variables
$SiteURL = "https://Crescent.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 -Interactive

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

Use the “-OverwriteIfAlreadyExists” switch to rename and replace the original file if it 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
}

This can be useful if you need to change the name of a large number of files at once.

How to rename a SharePoint Online site?

To change the URL of a SharePoint Online site, follow these steps:
Login to Modern SharePoint Admin Center >> Click on “Active Sites” under the “Sites” section >> Select the site collection you want to rename >> Click on the “Edit” link next to the site URL. Provide a new URL and hit the “Save” button.
More info: Rename a site collection in SharePoint Online

How do I Rename a document library in SharePoint Online?

To rename a list or document library in SharePoint Online, follow these steps: Navigate to your SharePoint Online list or library >> Click on the Settings Icon and then “List Settings”. In the List settings page, click on “List name, description and navigation” to update the Title of the list and click on “Save” to commit your changes.
More info: Rename a document library in SharePoint Online

Does renaming a file in SharePoint change the link?

If you share a file using the “Share” feature, it doesn’t change the link. (E.g.,https://Crescent.sharepoint.com/:i:/s/Retail/EawZ5OTNJQZGpq8PttH7-nmjEaBx3pSk2ygehAV). However, if you have shared a direct link to the file, that changes after the rename! (E.g., https://Crescent.sharepoint.com/sites/Retail/Documents/Invoices.xlsx).

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

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

  • Hello Salaudeen. Great posts thanks. I have a similar question to others on this post. An organisation has imported 100s of documents with generic names and now wants to replace those names with ‘better’ names. I am trying to find a way to replace the existing name with a variable, similar to the example below.
    Rename-PnPFile -ServerRelativeUrl $File[“FileRef”] -TargetFileName $NewFileName
    The two options I have looked at are (a) a csv that contains both the original and new names, (b) a new column in the same library that contains the new names. In both cases I cannot work out how to set up the variable that can be used.
    Any suggestions be much appreciated.
    Thanks

    Reply
  • Question, how would I go about renaming filenames from an excel csv across multiple libraries? Like I’ve got an excel csv with Source URL, Old Filename, New Filename that has a hundred files I need to rename but they aren’t in one library.

    Reply
  • Hi Salaudeen, I would like to use the PnP script to rename files, in my case, files were migrated in SPO with no extension from FileNet. I have the file names and extensions in a CSV along with their URLs which are spread across multiple libraries in a site. Could you help me understand how can I use the CSV as an input file for the PnP script?

    Reply
  • 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

Your email address will not be published. Required fields are marked *