【问题标题】:Auto rename files with sequential numbers and basename in powershell在powershell中使用序号和basename自动重命名文件
【发布时间】:2021-04-27 10:00:45
【问题描述】:

我有一些视频文件需要重命名。 名称是这样的:[视频名称] [编号].[文件扩展名] 我最近更换了需要特殊命名顺序的媒体播放软件。 顺序如下:[video name] e(increment start at 01)].[file-extension] 此外,媒体播放器需要这样的文件夹结构:C:\Media\[series]\[season(increment start at 01)] 我可以手动创建文件夹结构,也可以手动重命名文件,但我想自动化该过程以节省一些时间。

创建文件名的最佳方式如下:检查文件路径:

$path = Get-Location
get-childitem "$path" -recurse | where {$_.extension -eq ".mkv"} 

并检测 \season[number] 之前的路径。理想情况下,脚本会像这样重新生成文件:[video name = path(before season)],然后基于这样的脚本添加 e(increment start at 01)]:

$i = 1 Get-ChildItem *.mkv| %{Rename-Item $_ -NewName ('$_.Fullname{0:D4}.mkv' -f $i++)} 如此处所示:

Bulk renaming of files with powershell 但是,如果该系列有 12 集并且文件名如下:s01e001

,则媒体播放器会感到困惑

如果无法根据路径获取名称,我想要一个脚本,将文件重命名为 [series name] e[increment start from 01].mkv

有没有办法创建脚本来重命名文件?

【问题讨论】:

  • 请向我们展示一些真实的文件名。现在完全不清楚[video name] 包含什么以及如何从中解析[series name]
  • 真正的文件名应该是这样的:dr.谁 01.mkv 我想变成博士。谁s01e01.mkv。该文件将位于文件夹 Dr. who\Season 01 中,因此脚本应根据 \Season 01 上方的文件夹解析系列名称

标签: powershell rename


【解决方案1】:

这是我用于此目的的脚本:

Write-Output "Press Ctrl+c to Abort"
Write-Output ""
Write-Output "This Script will rename all files of a specified file type with a zero-padded sequential "
Write-Output "number like 01.jpg. An optional basename ending before file type can be added like 01-Jake.jpg"
Write-Output "Enter an integer not including the zero-padded numbers to start the sequential numbering."
[int]$startInt = Read-Host "Example 0 or 1 or 10... etc."

$file_type = Read-Host 'Enter the file type that you would like to target. Example: .jpg .png .m4v .mp4 .pdf'
# $fileNameEnding = Read-Host 'Add a file basename ending before its file type extension.'
$fileNameEnding = Read-Host 'Add an optional basename ending before file type extension. Enter it now or press enter to skip'

Get-ChildItem *$file_type | ForEach-Object{Rename-Item $_ -NewName ("{0:D2}$fileNameEnding$file_type" -f $startInt++)}

其中使用了 {0:D2},即填充的零的数量。所以 {0:D4} 将填充 4 个零。

您可以运行此脚本来查看如何访问文件名的不同部分。

$filePath = Read-Host 'Enter the file name and path to see its parts'
Write-Output ""
Write-Output "Extension: $((Get-Item $filePath ).Extension)"
Write-Output "Basename: $((Get-Item $filePath ).Basename)"
Write-Output "Name: $((Get-Item $filePath ).Name)"
Write-Output "DirectoryName: $((Get-Item $filePath ).DirectoryName)"
Write-Output "FullName: $((Get-Item $filePath ).FullName)"
Write-Output ""
Write-Output "Mode: $((Get-Item $filePath ).Mode)"

【讨论】:

  • 感谢您的回复。我测试了你的脚本,但由于某种原因它对我不起作用。它一直说找不到媒体的路径,即使我将其更改为 $path = Get-Location 并且它从未要求我输入扩展名等。我找到了一个似乎可以做我想做的软件只需要测试它。还是谢谢
  • 您应该从脚本的开头得到一两个问题。使用 Get-ExecutionPolicy 检查您的执行策略。如果设置为受限,则需要更改它。请参阅此Video。此外,脚本需要与要重命名的文件一起保存。当您运行将其路径引用为 .\ 或在其上方的文件夹中,将其路径引用为 ..\ 然后 cd 到脚本位置,键入:./script.ps1
猜你喜欢
  • 2018-03-17
  • 2021-11-15
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 2018-02-07
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多