Powershell使用excel引用列表批量重命名文件
我需要有关PowerShell的帮助 我将不得不开始重命名文件在每周的基础上,我将重命名超过100个每周或更多的动态名称每个 我要重命名的文件位于“C:Documents\Scans”中的文件夹名Scans。可以说,时间扫描是正常的 我在“C:Documents\Mapping\New file Name.xlsx”中有一个excel文件。 工作簿只有一张工作表,新名称将在A列中,有x行。如上文所述,每个单元格将有不同的变量 p请对您的建议发表意见,这样我就可以了解正在发生的事情,因为我是一名新的编码员Powershell使用excel引用列表批量重命名文件,powershell,Powershell,我需要有关PowerShell的帮助 我将不得不开始重命名文件在每周的基础上,我将重命名超过100个每周或更多的动态名称每个 我要重命名的文件位于“C:Documents\Scans”中的文件夹名Scans。可以说,时间扫描是正常的 我在“C:Documents\Mapping\New file Name.xlsx”中有一个excel文件。 工作簿只有一张工作表,新名称将在A列中,有x行。如上文所述,每个单元格将有不同的变量 p请对您的建议发表意见,这样我就可以了解正在发生的事情,因为我是一名新
谢谢大家的时间和帮助。您可能希望excel文件中有两列:
- 原始文件名
- 目标文件名
祝你好运。尽管我同意Ad Kasenally的观点,即使用CSV文件会更容易,但这里有一些东西可能对你有用
$excelFile = 'C:\Documents\Mapping\New File Name.xlsx'
$scansFolder = 'C:\Documents\Scans'
########################################################
# step 1: get the new filenames from the first column in
# the Excel spreadsheet into an array '$newNames'
########################################################
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$workbook = $excel.Workbooks.Open($excelFile)
$worksheet = $workbook.Worksheets.Item(1)
$newNames = @()
$i = 1
while ($worksheet.Cells.Item($i, 1).Value() -ne $null) {
$newNames += $worksheet.Cells.Item($i, 1).Value()
$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()
########################################################
# step 2: rename the 'scan' files
########################################################
$maxItems = $newNames.Count
if ($maxItems) {
$i = 0
Get-ChildItem -Path $scansFolder -File -Filter 'scan*' | # get a list of FileInfo objects in the folder
Sort-Object { [int]($_.BaseName -replace '\D+', '') } | # sort by the numeric part of the filename
Select-Object -First ($maxItems) | # select no more that there are items in the $newNames array
ForEach-Object {
try {
Rename-Item -Path $_.FullName -NewName $newNames[$i] -ErrorAction Stop
Write-Host "File '$($_.Name)' renamed to '$($newNames[$i])'"
$i++
}
catch {
throw
}
}
}
else {
Write-Warning "Could not get any new filenames from the $excelFile file.."
}
您能否向我们展示(部分)Excel内容,以便我们了解它是否包含完整路径和文件名,还是仅包含名称?是什么决定了“动态名称”“?这将是扫描,扫描时将文件保存为扫描1,依此类推。只需参考扫描文件夹即可。扫描的文件将按顺序排列,最新扫描的文件位于顶部。假设我扫描了100,顶部显示的是扫描100、扫描99、扫描98等等。在A列的excel文件中,将有100行,每个单元格值包含唯一的值。我需要PowerShell用excel中引用的新名称覆盖当前文件名。谢谢。代码工作正常。很抱歉出现延迟。