office-365-advent-calendar

Scenario

A short while ago, I had to update a fairly large number of documents in multiple libraries in a SharePoint Online site. Problem was that their file extension was .html which doesn’t display in the browser if stored in SharePoint Online, but rather these files get downloaded upon opening. The workaround – rename them to .aspx. The following scripts does this for all .html files and renames them to .aspx

Code

$cred = Get-Credential
Connect-PnPOnline -Url "http://mytenant.sharepoint.com/sites/demo" -Credentials $cred
$ctx = Get-PnPContext
$libraries = Get-PnPlist | Where{$_.BaseTemplate -eq 101}
foreach($lib in $libraries) {
	write-host "Getting items from $($lib.Title)"
	$items = Get-PnPListItem -List $lib -Fields "Title", "FileLeafRef" | where {$_["FileLeafRef"] -like "*.html"}
	write-host "Looping through the items"
	foreach($item in $items) {
		$file = $item.File
		$ctx.Load($file)
		$ctx.Load($file.ListItemAllFields)
		$ctx.ExecuteQuery()
		write-host "Renaming file $($file.Name)"
		$newName = $file.Name -Replace "\.html",".aspx"
		Move-PnPFile -ServerRelativeUrl $file.ServerRelativeUrl -TargetUrl "$($file.ListItemAllFields['FileDirRef'])/$($newName)" -Force
	}
}

3 thoughts on “Office 365 Advent Calendar – 23 Bulk-updating File Extensions in SharePoint Online with PowerShell”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.