2014-04-08 53 views
-2

我需要一個批處理腳本, 我寫一個批處理腳本的文件夾重命名爲一個數字,這個數字不應該是一樣的..我每次點擊的批處理文件,它應該是一個隨機數。重命名文件夾到一個隨機數

如: 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

問題什麼的一部分您有問題? – wimh

回答

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多個文件夾,所以要小心。

+0

編輯你的答案,我要刪除我的;-) – Stephan

+0

@Stephan感謝。當我看到問題時,我有一個地方,所以我沒有太多時間。 – 09stephenb

1

此批處理文件保存有關其自身內部的最後一個文件夾名稱的信息。每次運行時,它都會檢索這些信息。如果找不到,則假定溫度。如果文件夾不存在,則會創建該文件夾。如果存在,則搜索新名稱,重命名該文件夾並將該信息保存在批處理文件中。

@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=: