There is no direct function to rename a uploaded document in SharePoint document library using the client side object model (csom), as a work-around, we need to use File.MoveTo method to rename a file. Here we need to actually move the file in same location with different name.
Use the below powershell script to rename a specific sharepoint document file.
#Add required references to SharePoint client assembly to use CSOM [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") $siteUrl = "https://spotenant.sharepoint.com/sites/contosobeta" $UserName = "[email protected]" $SecPwd = $(ConvertTo-SecureString 'adminPassword' -asplaintext -force) $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$SecPwd) $ctx.credentials = $credentials #Rename a file $fileUrl ="/sites/contosobeta/Shared Documents/test.csv" $newfileUrl="/sites/contosobeta/Shared Documents/test_rename.csv" $file = $ctx.Web.GetFileByServerRelativeUrl($fileUrl) $file.MoveTo($newfileUrl, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite) $ctx.ExecuteQuery()
Rename a file using Office Dev PnP
You can also use below powershell code to rename a document stored inside a SharePoint Online document library using Office Dev PnP.
Connect-SPOnline -url [yoururl] $ctx = Get-SPOContext $web = Get-SPOWeb $fileUrl ="/sites/contosobeta/Shared Documents/test.csv" $newfileUrl="/sites/contosobeta/Shared Documents/test_rename.csv" $file = $web.GetFileByServerRelativeUrl("$fileUrl") $file.MoveTo("$newfileUrl", 'Overwrite') $ctx.ExecuteQuery()
Rename all uploaded document files in a SharePoint List
You can also use the below powershell script to rename all the files in a document library.
$siteUrl = "https://spotenant.sharepoint.com/sites/contosobeta" $UserName = "[email protected]" $SecPwd = $(ConvertTo-SecureString 'adminPassword' -asplaintext -force) $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,$SecPwd) $ctx.credentials = $credentials #Load items $list = $ctx.Web.Lists.GetByTitle("Documents") $query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery() $items = $list.GetItems($query) $ctx.Load($items) $ctx.ExecuteQuery() #Rename File(s) foreach ($item in $items){ if($item.FileSystemObjectType -eq [Microsoft.SharePoint.Client.FileSystemObjectType ]::File) { $destFileUrl = $item["FileRef"].ToString().Replace("test","test_rename") $item.File.MoveTo($destFileUrl, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite) $ctx.ExecuteQuery() } }
Advertisement