Change File Name in SharePoint Document Library Via PowerShell

In this hint, I will elaborate How to Rename a file in a SharePoint Document Library Via PowerShell.

Steps :

  • Open SharePoint Managment Shell as Administrator.

Run SharePoint Management Shell as Administrator - Devoworx

  • Edit the following code with your entries ($Web,$DocLib,$filename) >  Paste it in SharePoint Management Shell > Enter.
$Web = Get-SPWeb "http://epm/workflow"
$DocLib = $Web.Lists["Doc"] #your Doc Library Name
$filename = "Qassas.pdf" #the file name that you need to change
foreach($ListItem in $DocLib.Items)
{
if($ListItem["Name"] -eq $filename)
{
if( $ListItem.CheckOutStatus -ne "None" ) #if the file is not checked out
{
  $ListItem.File.CheckOut() #check the file out
  $ListItem["Name"] = "Your New Name" #set the new file name
  $ListItem["Title"] = "Your New Title" #set the new file title
  $ListItem.Update()
  $ListItem.File.CheckIn("File Name Updated") #check in
}
ELSE # if the file is checked out
{
  $ListItem["Name"] = "Your New Nameqq"
  $ListItem["Title"] = "Your New Title"
  $ListItem.Update()
  $ListItem.File.CheckIn("File Name Updated") }
} }

rename-a-file-within-a-document-library-in-sharepoint-via-powershell

  • Go back to the Doc library > Select the file > View Properties. The File Name and its Title should be now renamed properly as shown below :

rename-file

Note : If you need to replace a specific word at your file name within document library in SharePoint via PowerShell you can use the following script

$Web = Get-SPWeb "http://epm/workflow"
$DocLib = $Web.Lists["Doc"] #your Doc Library Name
$filename = "Qassas 2015.pdf" #the file name that you need to change
foreach($ListItem in $DocLib.Items)
{
if($ListItem["Name"] -eq $filename)
{
if( $ListItem.CheckOutStatus -ne "None" ) #if the file is not checked out
{
$ListItem.File.CheckOut() #check the file out
$ListItem["Name"] = $ListItem["Name"].replace("2015","2016") #replace
$ListItem["Title"] = $ListItem["Title"].replace("2015","2016")
$ListItem.Update() $ListItem.File.CheckIn("File Name Updated") 
#check in } 
ELSE # if the file is checked out 
{ $ListItem["Name"] = $ListItem["Name"].replace("2015","2016")
  $ListItem["Title"] =$ListItem["Title"].replace("2015","2016")
  $ListItem.Update() $ListItem.File.CheckIn("File Name Updated") } 
} }

Enjoy 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s