Forum Discussion

ZGeek1090's avatar
ZGeek1090
Copper Contributor
Aug 03, 2023

Rename files in OneDrive or SharePoint Document Library

Hello,

I've been trying to rename files in OneDrive Business or SharePoint Document Library but have only been able to get as far as renaming the files locally.

 

My goal is to rename files in a SharePoint document library subdirectory (or OneDrive), where Powershell will rename the files based on data from Excel columns/rows. 

 

The Document Library contains files named: 1234-0087-080323.pdf 

My Excel file (or I can create a SharePoint list if needed) has two columns;

Column A is the Account Number; for example "888-0087".

I would like to look up the Excel file and rename the file if it contains a part of Column A, the account number (i.e. 0087), then rename it to the corresponding account name in Column B.

 

ColumnA ColumnB

Account NumberAccount Name
888-0087Account

 

Here's what I have so far:

 

$excelFile = 'C:\test\test.xlsx' # xlsx being with Name in col 1 and acct # in col 2
$tempFolder = 'C:\test\temp\' # where the files to be renamed live

 

#opens workbook
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$workbook = $excel.Workbooks.Open($excelFile)
$worksheet = $workbook.Worksheets.Item(1)


$i = 1
while ($worksheet.Cells.Item($i, 1).Value() -ne $null) {
$id_no = $worksheet.Cells.Item($i, 2).Value()
$old_f = Get-ChildItem $tempFolder | Where Name -match ($id_no) | Select FullName
if ($old_f.FullName -ne $null) {
$start = $tempFolder.Length + $id_no.Length
$datestr = $old_f.FullName[$start..$old_f.FullName.Length] -join ''
$new_f = ($worksheet.Cells.Item($i, 1).Value() + $datestr)
if (Test-Path -Path $old_f.FullName) {
if ((Test-Path -Path $tempFolder$new_f) -eq $true) {
Write-Host $tempFolder$new_f "already exists. NOT RENAMED"
}
if ((Test-Path -Path $tempFolder$new_f) -eq $false) {
Rename-Item -Path $old_f.FullName -NewName $new_f
Write-Host $old_f.FullName "renamed to" $new_f
}
}
}

$i++
}

$excel.Quit


# IMPORTANT: clean-up used Com objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

No RepliesBe the first to reply