如何在批处理文件中为文件夹中的每个文件随机生成名称?

The*_*der 3 windows random cmd batch-file file-rename

我想将文件夹中的所有文件重命名为随机名称,但它想将所有文件重命名为相同的名称:

ren "c:\Test\*.txt" %Random%.txt
pause
Run Code Online (Sandbox Code Playgroud)

输出:

C:\Users\Oliver\Desktop>ren "c:\Test\*.txt" 9466.txt
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.

C:\Users\Oliver\Desktop>pause
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

有人知道如何为批处理文件中的文件夹中的每个文件随机生成名称吗?

asc*_*pfl 5

在像 这样的命令行中ren "C:\Test\*.txt" "%RANDOM%.txt"%RANDOM%仅展开一次,因此它尝试将每个文件重命名为相同的名称。

要单独重命名每个文件,您需要循环遍历所有文件。
为此,需要延迟扩展——请参阅set /?

这是批处理文件解决方案:

@echo off
setlocal EnableDelayedExpansion
for %%F in ("C:\Test\*.txt") do (
    ren "%%~F" "!RANDOM!.txt"
)
endlocal
Run Code Online (Sandbox Code Playgroud)

这是命令行变体:

cmd /V:ON /C for %F in ("C:\Test\*.txt") do ren "%~F" "!RANDOM!.txt"
Run Code Online (Sandbox Code Playgroud)

请注意,!RANDOM!还可能返回上面代码中未考虑的重复值。