繁体   English   中英

使用批处理或从批处理运行的Powershell重命名文件夹中的所有文件

[英]Rename all files in folder using batch or powershell run from batch

我在一个文件夹中有随机文件名和扩展名的文件,文件夹中还有另一个包含* .htm扩展名的随机文件名。 我想重命名文件夹中每个随机文件的所有文件名,以匹配一个* .htm文件,同时保留每个随机文件的正确扩展名。

因此,当运行批处理文件时,将检测到诸如“我的文件名.HTM”之类的文件,并将以下文件重命名为:

  • “ test.doc”重命名为“我的文件名.doc”

  • “ anyfile.jpg”重命名为“我的文件名.jpg”

  • “ text.txt”重命名为“我的文件名.txt”

我努力了

Rename "*.*" "*.htm"

没有成功。 * .HTM文件可以是任何未知的文件名,但始终包含HTM扩展名,并且它始终是文件夹中唯一具有HTM扩展名的文件。 然后,我将从命令行运行批处理文件。

简洁的批处理文件:

for %%f in (*.htm) do set name=%%~nf
ren * "%name%.*"

与n01d的答案相同。 另外,不要将批处理文件放在同一目录中。

编辑:

这是一个示例会话,显示该批处理文件将所有文件重命名为.htm文件的名称:

D:\tmp\kktmp>dir
 Volume in drive D has no label.
 Volume Serial Number is 4EDE-41E1

 Directory of D:\tmp\kktmp

14/07/2016  12:06    <DIR>          .
14/07/2016  12:06    <DIR>          ..
14/07/2016  12:05                 0 Author Name - Book Title - The Billionaires Revenge.htm
14/07/2016  12:06                 0 Book Title - The Billiona - Author Name.azw3
14/07/2016  12:06                 0 Book Title - The Billiona - Author Name.epub
14/07/2016  12:06                 0 Book Title - The Billiona - Author Name.mobi
14/07/2016  12:06                 0 Book Title - The Billiona - Author Name.pdf
               5 File(s)              0 bytes
               2 Dir(s)  52,725,227,520 bytes free

D:\tmp\kktmp>type ..\t.bat
for %%f in (*.htm) do set name=%%~nf
ren * "%name%.*"

D:\tmp\kktmp>..\t.bat

D:\tmp\kktmp>for %f in (*.htm) do set name=%~nf

D:\tmp\kktmp>set name=Author Name - Book Title - The Billionaires Revenge

D:\tmp\kktmp>ren * "Author Name - Book Title - The Billionaires Revenge.*"

D:\tmp\kktmp>dir
 Volume in drive D has no label.
 Volume Serial Number is 4EDE-41E1

 Directory of D:\tmp\kktmp

14/07/2016  12:37    <DIR>          .
14/07/2016  12:37    <DIR>          ..
14/07/2016  12:06                 0 Author Name - Book Title - The Billionaires Revenge.azw3
14/07/2016  12:06                 0 Author Name - Book Title - The Billionaires Revenge.epub
14/07/2016  12:05                 0 Author Name - Book Title - The Billionaires Revenge.htm
14/07/2016  12:06                 0 Author Name - Book Title - The Billionaires Revenge.mobi
14/07/2016  12:06                 0 Author Name - Book Title - The Billionaires Revenge.pdf
               5 File(s)              0 bytes
               2 Dir(s)  52,724,703,232 bytes free

像这样:

$files = Get-ChildItem -Path D:\TEST_123
$htmBaseName = $files | where {$_.Extension -eq '.htm'} | select -ExpandProperty BaseName

foreach ($f in $files) {
    if ($f.Extension -ne '.htm') {
        Rename-Item -Path $f.FullName -NewName ($htmFileName + $f.Extension)
    }
}

但是要小心:如果有多个具有相同扩展名的文件。 您将得到一个错误Cannot create a file when that file already exists

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM