I need a batch script,
I am writing a batch script for renaming a folder to a number and that number should not be the same.. Every time I click the batch file, it should be a random number.
eg:
folder name is "temp"
If I run the bat file that folder name should be change to a random number.
eg:
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"
please teach me how to do this..
I am a newbie in this field..
This batch file saves the information about the last folder name inside itself. Each time it is run, it retrieves this information. If not found, temp is assumed. If folder does not exist, it is created. If it exists, a new name is searched, the folder is renamed and the information saved inside batch file.
#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
And no, the added semicolon in labels is not a typo error. They (or other character) are needed to avoid problems with the delims=:
I have made this for you:
#echo off
:retry
SET /A test=%RANDOM% * 10000 / 100000 + 1
echo %test%
IF EXIST %~dp0\%test% GOTO retry
md "%~dp0\%test%"
GOTO retry
It's quite quick 100+ folders per second, so watch out.
Related
I'm trying to create a batch file script that will compress all subfolders named folder1 within a directory, BUT it should only compress this folder if it does NOT contain another subfolder with the same name.
I am very new to cmd and batch files, and this is also my first post of stack overflow, please let me know if I've failed to give some information that I should!
The bit of pseudo-ish code below hopefully illustrates what I'm trying to accomplish:
#echo off
SETLOCAL EnableDelayedExpansion
FOR /D /R %%G IN (*folder1*) DO (
CD %%G
SET /A compress=true
FOR /D /R %%H IN (*folder1*) DO (
ECHO folder contains another folder of same name, should not be compressed
SET /A compress=false
)
IF !compress!==true (
ECHO Run compression operation on folder
"C:\Program Files (x86)\7-zip\7z.exe" a -tzip "%%G.zip" "%%G\"
)
)
Please ask away if anything seems unclear! I'm really hoping to turn the above into functional code, thank you in advance for any input or thoughts.
#ECHO OFF
SETLOCAL
:: Starting directory
SET "sourcedir=U:\sourcedir"
:: name of directory to compress
SET "targetname=targetdir"
FOR /d /r "%sourcedir%" %%a IN (*) DO (
IF /i "%%~nxa" == "%targetname%" IF NOT EXIST "%%a\%targetname%\." (
ECHO compress %%a
rem temporarily switch to target directory
PUSHD "%%a"
ECHO 7z a -tzip "%%a.zip"
rem back to original directory
POPD
)
)
GOTO :EOF
This should do as you want - it will echo not execute the 7z command.
The if sees whether the "name and extension" portion of the directory-name in %%a matches the target (the /i makes the match case-insensitive). If it matches AND there is a subdirectory with the required name, then the compression portion is executed.
There are two points to consider.
First, the name of the destination ZIP file. As you have written it, the ZIP generated would be folder1.zip in the parent directory. IDK what you want here. This code would do the same, but %%a.zip could be replaced by ..\%targetname%.zip since the pushd/popd changes the current directory to the folder1 directory and .. means the parent directory.
The second matter is whether or not you want to compress ...\folder1\folder1 (which would have a destination ZIP file of ...\folder1\folder1.zip)
Revision given comment:
#ECHO OFF
SETLOCAL
:: Starting directory
SET "sourcedir=U:\sourcedir"
:: name of directory to compress
SET "targetname=targetdir"
REM (
FOR /d /r "%sourcedir%" %%a IN (*) DO IF /i "%%~nxa" NEQ "%targetname%" (
rem calculate parent name in %%~nxp and grandparent in %%~nxg
FOR %%p IN ("%%~dpa.") DO FOR %%g IN ("%%~dpp.") DO (
IF /i "%%~nxp" == "%targetname%" IF /i "%%~nxg" NEQ "%targetname%" (
ECHO child %%~nxa
ECHO parent %%~nxp
ECHO Gparent %%~nxg Gppath=%%~dpg
ECHO compress %%a
rem temporarily switch to target directory
PUSHD "%%a"
ECHO 7z a -tzip "%%a.zip"
ECHO -------------------
rem back to original directory
POPD
)
)
)
GOTO :EOF
It's not that clear what you want to do with a directory named ...\folder1\folder1\something or what the target ZIP file-name should be.
The if in the for /d /r line will ensure that only leaf-names that do not match the target name are processed. The path-name in %%a is then processed into the parent and grandparent portions - note that %%~dp? is the drive+path portion of %%? which terminates \ so appending . to this resolves to effectively removing the terminal \ yielding a "filename".
You appear to want to compress directories that have a parent but not a grandparent named with the target string, hence the innermost if statement.
I've just echoed the various strings available at this point so they may be strung together as required to form your destination ZIP file-name. Note that the pushd/popd bracket ensures that the current directory at the time of the compress is the leaf to be compressed.
I am in the middle of batch extracting screenshots for contents we are planning to use on a tube site I am working on.
The jpeg files per content is labled as followed:
6c82c0239f6eb839-1
6c82c0239f6eb839-2
all the way to 120
The file name is different per content
a82384e2c46ba4af-1
a82384e2c46ba4af-2
etc.
They will all be extracted to a singe folder.
So I basically need a batch file that will create folders based on the content name without the dash and number and move all 120 jpegs in the folder with the content name.
For example:
Create folder named 6c82c0239f6eb839 and
move 6c82c0239f6eb839-1 to 6c82c0239f6eb839-120 in to the created folder.
I saw another thread with the following batch file. its pretty much what I want but the folder name is only 3 characters long and the files are copied to the newly created folders instead of moving them.
#echo off
SetLocal EnableDelayedExpansion
for /F "delims=" %%a in ('dir /b *.jpeg') do (
set Name=%%a
set Folder=!Name:~0,3!
xcopy /y "%%a" !Folder!\
)
Could someone change this so that it will display full file name without the dash and number for the folders and move files in its respective folders instead of copy?
Thank you
#echo off
setlocal
#rem Get each jpeg file.
for /F "delims=" %%A in ('2^>nul dir /b *.jpeg') do (
rem Get filename as token before the dash.
for /f "delims=-" %%B in ("%%~A") do (
rem Make dir if needed.
if not exist "%%~B" md "%%~B"
rem Check if isdir.
2>nul pushd "%%~B" && popd
if errorlevel 1 (
>&2 echo Failed isdir "%%~B".
) else (
rem Do the move operation.
>nul move /y "%%~A" "%%~B"
if errorlevel 1 (
>&2 echo Failed move "%%~A" to "%%~B"
)
)
)
)
exit /b %errorlevel%
The code is well remarked so if you want to understand
the evaluated code by changing #echo off to #echo on.
The use of %errorlevel% after the exit /b is not
required though will let you know what the errorlevel is
when #echo on is used.
The pushd tests for a directory
(even if it is a symlink).
errorlevel is checked to decide if to echo a
error message or do the move.
As the for loop variables are used direct, use of
enabledelayedexpansion is not needed.
Many commands support the argument of /? to get help
about the command. i.e. move /?.
If you only try to copy the correct jpeg to the correct folder, you can do this:
#echo off
SetLocal EnableDelayedExpansion
CD <CORRECT ROOT PATH>
for /F "delims=" %%a in ('dir /b *.jpeg') do (
set Name=%%a
REM I presume all the files have 16 characters before the dash
set Folder=!Name:~0,16!
IF NOT EXIST !Folder! MKDIR !FOLDER!
xcopy /y "%%a" !Folder!\
)
I was not able to test.
First of all, I would like to apologize for my manners regarding my initial post.
The answer by micheal_heath has resolved my issue.
Furthermore, I happened to find this post by user Salmon Trout from a different site which also worked.
Batch file to make folders with part of file name and then copy files
#echo off
setlocal enabledelayedexpansion
for %%A in (*.psd *.jpg) do (
echo file found %%A
for /f "delims=" %%B in ("%%A") do set fname=%%~nB
for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
for /f "tokens=1* delims=_" %%D in ("!fname!") do set folname=%%D
echo folder name !folname!
if not exist "!folname!" (
echo Folder !folname! does not exist, creating
md "!folname!"
) else (
echo Folder !folname! exists
)
echo Moving file %%A to folder !folname!
move "%%A" "!folname!"
)
echo Finished
pause
I just changed the the following line remove the hypen and numbers to create folders for the file name properly.
for /f "tokens=1* delims=-***" %%D in ("!fname!") do set folname=%%D
I still lack the knowledge on why and how both methods work, but this has been an interesting start for me. I hope other beginners trying to solve a similar issue can find something useful from this post.
I have a folder containing many files named as such: JBMA_23456.docx, JMRI_21456.docx, CM_22554.docx, QUA_11224.docx. How do I create a sub-folder for each file bearing the same name as the file but without the .docx file extension? Additionally, I want to store the filename only as variables.
For example, I need to create a sub-folder named JBMA_23456 from the document
JBMA_23456.docx. Can anyone point me in teh right direction?
#echo off
for %%A in (*.docx) do if not exist "%%~nA" md "%%~nA"
This creates a folder with the same name as each .docx file.
View modifiers in for /? or in call /?. The n modifier is the name.
Path modifiers:
dpnx is drive, path, name and extension.
Here's an example batch file which attempts to perform the tasks as laid out in your question:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "BaseDir=C:\Users\Compo\Desktop\test"
Set "FileExt=.docx"
For /F "Delims==" %%A In ('Set var[ 2^>Nul') Do Set "%%A="
Set "i=0"
For /F "Delims=" %%A In ('Where "%BaseDir%":*%FileExt% 2^>Nul') Do (Set /A i+=1
Call Set "var[%%i%%]=%%~nA"
If Exist "%%~dpA%%~nA\" (Echo Sub-Folder %%~nA already exists in %BaseDir%
) Else (Set /P "=Creating sub-folder %%~nA in %BaseDir%"<Nul
MD "%%~dpA%%~nA">Nul 2>&1 && (Echo= was successful) || Echo= failed))
Set var[ 2>Nul
Pause
In order to use it, you would first ensure that the directory holding your files, (excluding any trailing backslash), is placed between the = and " on line 4, and the single file extension, (including the leading period, .), similarly on line 5.
It is not entirely clear what you are asking for...
Anyway, here is the code i made
echo off
chcp 65001
cls
for /f "usebackq delims=." %%0 in (`dir /b "*.docx"`) do (
set filename=%%0
md %filename%
)
cmd /k
It creates a new folder for every file. Feel free to ask if this was not what you expected
I hope someone can help me with my problem.
There is a directory containing folders for every order, e.g.
L:\Med_Department\Orders\
L:\Med_Department\Orders\T0012345_AB100_CustomerA_site2
L:\Med_Department\Orders\T0012346_CD350-CustomerB site1
...
How can I get the full name of a folder by searching for the order number.
When I enter the order number for example:
T0012345
,
I want the script to store
T0012345_AB100_CustomerA_site2
in a variable so I can use it to create the folder for my new project instead of the order number.
The order number is unique and has the format Txxxxxxx . The rest of the folder name can be separated by underscore, blank space or other characters.
If the order number is not found (e.g. order number not entered correctly) the user should enter the order number again.
This is what I achieved so far.
I enter the order number and the script copies a template folder into my projects directory with the order number as folder name.
#Echo off
rem directories
set template= "N:\Documentation\New_folder_OrderNo-Type-Customer-site"
set dirOrder= "L:\Med_Department\Orders\"
SET dirProjects= "Z:\Projects\2016\"
rem input Order No.
echo Please enter the order number?
echo.
set /p OrderNo=OrderNo:
rem target directory
set dirNewProject=%dirProjects%%OrderNo%\
echo %dirnewProject%
pause
rem copy content from template into target directory
xcopy %template% %dirNewProject% /S /E /C /H /O /R /Y /D /V
rem open target directory
explorer %dirNewProject%
;exit
Thanks in advance.
something like this:
#Echo off
rem directories
set template= "N:\Documentation\New_folder_OrderNo-Type-Customer-site"
set dirOrder = "L:\Med_Department\Orders\"
SET dirProjects= "Z:\Projects\2016\"
:again
rem input Order No.
echo Please enter the order number?
echo.
set /p OrderNo=OrderNo:
if not exist "%dirOrder%%OrderNo%\" (
echo order %OrderNo% not found
goto :again
)
:: the rest of the script
:: ...
?
use a for to get the output of a command. Use dir with proper switches to do a wildcard search (Note: with dir wildcards do only work within the very last element of a path).
:again
set /p "OrderNo=OrderNo: "
set "folder=none"
for /f "delims=" %%a in ('dir /s /ad /b %dirOrder%%OrderNo%*') do set folder=%%a
if %folder% == none goto :again
echo found: %folder%
see for /? and dir /? for details
You can simply use for /D against the pattern %OrderNo%*. If there is folder whose name starts with %OrderNo% (there should be one only, if I got it right), dirNewProject is going to hold its path; if there is none, the variable is going to be empty. You can chek if [not] defined dirNewProject afterwards and jump to a :LABEL contitionally:
rem (skipping data entry part of script)
rem directory
set "dirNewProject="
for /D %%I in ("%dirProjects%\%OrderNo%*") do set "dirNewProject=%%I"
if not defined dirNewProject goto :LABEL
rem (skipping file copy part of script)
Example...(Untested)
#Echo Off
SetLocal
Rem directories
(Set template=N:\Documentation\New_folder_OrderNo-Type-Customer-site)
(Set dirOrder=L:\Med_Department\Orders)
(Set dirProjects=Z:\Projects\2016)
Rem exit if above directories do not exist
For %%a In (template dirOrder dirProjects) Do (If Not Exist "%%%%a%%\" Exit/B)
Rem make search dir current
If /I Not "%CD%" Equ "%dirOrder%" PushD %dirOrder%
:AskNum
Rem input Order No.
Echo(
Echo( Please enter the order number?
Echo(
Set/P "OrderNo=OrderNo: "
For /D %%a In ("%OrderNo%*") Do (Set OrderDir=%%~a)
If Not Defined OrderDir (Choice /C /M "Would you like to try again?"
If Errorlevel 2 Exit/B
GoTo :AskNum)
Rem new project directory
(Set dirNewProject=%dirProjects%\%OrderDir%)
Rem copy content from template to new project directory
If Not Exist "%dirNewProject%\" (
RoboCopy "%template%" "%dirNewProject%" /E /Copy:DATSO)
Rem open new project directory
Explorer "%dirNewProject%"
Is it possible to make a batch file that will rename a folder if does not have a specific name?
EG:
Parent Directory
- - - > info
- - - > randomfoldername
I have many folders that follow the above pattern. What I would like to do is make a batch file that will rename "randomfoldername" in this structure. There is always two folders in the Parent Directory, one is always "info" and the other changes for each case. Is there a method within a batch file that I could use to always rename the "randomfoldername" directory? I was thinking something along the lines of,
IF NOT == "info" THEN ren... ect.
Is this possible?
you can first check if folder exist then rename folder
if not exist c:\info ( call random.bat )
random.bat:
dir /A:D /b | findstr.exe /n /R "." > s:\sites\file-count.txt
FOR /F "tokens=1-10 delims=:" %%A IN ('type "s:\sites\file-count.txt"') do
set NUMBER-OF-FILES=%%A
FOR /L %%A IN (1,1,%number-of-files%) DO CALL RENAME.bat %%A
rename.bat
:rename
FOR /F "tokens=1-10 delims=:" %%A IN ('type "s:\sites\file-count.txt" ^|
findstr "%1:"') do ren %%B %RANDOM%%%B
also u can use free tool like Bulk Rename Utility
that app has cli for use in bat file here
also You can use powershell script like
$a = test-path c:\info
if ( $a -eq "True" ) { Write-Host nothing to do } Else { gic -directory path | %{$n="$pwd\$((get-random).tostring())$($_.name)";$_.moveto($N)} }
Next script starts with basic checks on command line parameter passed into.
FOR /F loop against the results of another command (dir) used. Next explanation stolen (see dbenham's original) :
FOR /R (as well as the simple FOR) begin iterating immediately, before
it has finished scanning the disk drive. It is possible for the loop
to reiterate the already named file! This would cause it to be renamed
twice, giving the wrong result. The solution is to use FOR /F with
command 'DIR /B', because FOR /F always processes the command to
completion before iterating.
#ECHO OFF >NUL
SETLOCAL enableextensions disabledelayedexpansion
set "ParentDirectory=%*"
if "%ParentDirectory%"=="" goto :usage1
if not exist "%ParentDirectory%\" goto :usage2
if not exist "%ParentDirectory%\info\" goto :usage3
set "SpecificName=Desired Name"
set /A "count=0"
for /F "delims=" %%G in ('dir /B /A:D "%ParentDirectory%\"') do set /A "count+=1"
if %count% neq 2 goto :usage4
for /F "delims=" %%G in ('dir /B /A:D "%ParentDirectory%\"') do (
if /I not "%%~G"=="info" (
if /I not "%%~G"=="%SpecificName%" (
echo renaming "%ParentDirectory%\%%~G" to "%SpecificName%"
rename "%ParentDirectory%\%%~G" "%SpecificName%"
) else (
echo renamed already: "%SpecificName%"
)
)
)
:endlocal
ENDLOCAL
goto :eof
:usage1
echo no paramater
goto :endlocal
:usage2
echo "%ParentDirectory%" folder does not exist
goto :endlocal
:usage3
echo "%ParentDirectory%\info" folder does not exist
goto :endlocal
:usage4
echo "%ParentDirectory%" folder contains %count% subfolders
goto :endlocal
Output:
==>29376745.bat
no paramater
==>29376745.bat x y
"x y" folder does not exist
==>29376745.bat d:\test
"d:\test\info" folder does not exist
==>md "d:\test\info"
==>29376745.bat d:\test
"d:\test" folder contains 6 subfolders
==>29376745.bat d:\test\29376745
renaming "d:\test\29376745\currentName" to "Desired Name"
==>29376745.bat d:\test\29376745
renamed already: "Desired Name"
==>
Required reading (indexes only):
An A-Z Index of the Windows CMD command line
Windows CMD Shell Command Line Syntax