I have a script that updates the filename and title on SharePoint from an excel file that lists the names, titles, and url. However, when trying to test run it says it cannot find the file. I have confirmed the URL and filename are correct so I'm a bit stumped - any help is appreciated!
*Error updating file 'EXAMPLE.PDF' with URL 'https://ABC.sharepoint.com/sites/DEF/GHI/JK/LMNO/PQ/RS/EXAMPLE.PDF': File Not Found.
*
Error updating file '' with URL '': Cannot bind argument to parameter 'Url' because it is null.
Import-Module SharePointPnPPowerShellOnline -DisableNameChecking
# Set variables for the SharePoint Online site and the Excel file
$siteUrl = "https://ABC.sharepoint.com/sites/DEF"
$excelFile = "C:\Users\ABC\OneDrive\Documents\FileRename.xlsx"
# Set up error logging
$errorLogPath = "C:\Users\ABC\OneDrive\Documents\ErrorlogRename.txt"
if (Test-Path $errorLogPath) {
Clear-Content $errorLogPath
} else {
New-Item -ItemType File -Path $errorLogPath -Force | Out-Null
}
# Connect to SharePoint Online
Connect-PnPOnline -Url $siteUrl
# Load the Excel file
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Open($excelFile)
$worksheet = $workbook.Worksheets.Item(1)
# Loop through each row in the Excel file and update the corresponding SharePoint items
for ($i = 2; $i -le $worksheet.UsedRange.Rows.Count; $i++) {
# Get the values from the Excel file
$existingFilename = $worksheet.Cells.Item($i, 1).Value2
$newFilename = $worksheet.Cells.Item($i, 2).Value2
$existingTitle = $worksheet.Cells.Item($i, 3).Value2
$newTitle = $worksheet.Cells.Item($i, 4).Value2
$documentUrl = $worksheet.Cells.Item($i, 5).Value2
# Get the SharePoint item ID from the document URL
try {
$file = Get-PnPFile -Url $documentUrl -ErrorAction Stop
$itemId = $file.ListItemAllFields.Id
$listName = $file.List.Title
# Update the SharePoint item
$itemProperties = @{}
if ($newFilename) {
$itemProperties.Add("FileLeafRef", $newFilename)
}
if ($newTitle) {
$itemProperties.Add("Title", $newTitle)
}
Set-PnPListItem -List $listName -Identity $itemId -Values $itemProperties
# Rename the file
if ($newFilename) {
Rename-PnPFile -ServerRelativeUrl $documentUrl -TargetFileName $newFilename
}
}
catch {
# Log the error
$errorMessage = "Error updating file '$existingFilename' with URL '$documentUrl': $($_.Exception.Message)"
Add-Content -Path $errorLogPath -Value $errorMessage
}
}
# Close the Excel file and quit Excel
$workbook.Close()
$excel.Quit()