将文件夹重命名为随机数

时间:2014-04-08 07:54:33

标签: batch-file

我需要一个批处理脚本, 我正在编写一个批处理脚本,用于将文件夹重命名为数字,并且该编号不应该相同。每次单击批处理文件时,它应该是一个随机数。

例如: folder name is "temp"

如果我运行bat文件,那么文件夹名称应该更改为随机数。

例如:

1st time : folder name after rename can be "34324"<br/>
2nd time : folder name after rename can be "29389"<br/>
.
.
.
.
.
nth time : folder name after rename can be "xxxxx"

请教我如何做到这一点..

我是这个领域的新手..

2 个答案:

答案 0 :(得分:1)

我已经为你做了这个:

@echo off
:retry
SET /A test=%RANDOM% * 10000 / 100000 + 1
echo %test%
IF EXIST %~dp0\%test% GOTO retry
md "%~dp0\%test%"
GOTO retry

每秒100多个文件夹非常快,所以要小心。

答案 1 :(得分:1)

此批处理文件保存有关最后一个文件夹名称的信息。每次运行时,它都会检索此信息。如果未找到,则假定为temp。如果文件夹不存在,则创建该文件夹。如果存在,则搜索新名称,重命名文件夹并将信息保存在批处理文件中。

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Determine where to work
    if "%cd:~-1%"=="\" ( set "where=%cd%" ) else ( set "where=%cd%\" )

    rem Determine what to search for in the current file
    set "testString=:::set lastName=[0-9][0-9]*"

    rem Retrieve the last name used
    set "lastName="
    for /f "tokens=* delims=:" %%a in ('findstr /r /b /e /c:"%testString%" "%~f0"') do %%a
    if not defined lastName set "lastName=temp"

    rem If the last folder does not exist, create it and finish
    if not exist "%where%%lastName%\" (
        mkdir "%where%\%lastName%" 
        echo(Folder [%lastName%] has been created
        goto endProcess 
    )

    rem Search for a new name
;:newNameLoop
    set "newName=%random%"
    if "%newName%"=="%lastName%" goto newNameLoop
    if exist "%where%%newName%" goto newNameLoop

    rem Rename the folder to the new name
    ren "%where%%lastName%" "%newName%" 2>nul && set "save=1" || set "save="

    rem If there were no problems, save the new name in current batch file
    if defined save (
        for /f "tokens=1,* delims=:" %%a in ('findstr /n /r /b /e /v /c:"%testString%" "%~f0" ^& break ^> "%~f0"') do >>"%~f0" echo(%%b
        >>"%~f0" echo(:::set lastName=%newName%
        echo Renamed [%lastName%] into [%newName%]
    ) else (
        echo Rename operation failed. Ensure folder is not in use
    )

    rem End of the process, clean and exit
;:endProcess
    endlocal
    exit /b

不,标签中添加的分号不是拼写错误。他们(或其他角色)需要避免delims=:

的问题