Search code examples
batch-filebatch-processingbatch-rename

How to Rename a Folder using Batch-Processing in Windows?


I am new to Batch programming and use MacBook to code, thus unable to run this piece of code that is supposed to rename a folder.

Can anyone help me to know If it renames a folder successfully or not ? If not, give possible solutions.

@echo off
echo Rename a Folder
set /p ON=Name of the folder to rename:
set /p NN=New folder name:
ren %ON% %NN%
echo a folder has been renamed
pause

Solution

  • You could make your script better by using doublequotes and checking the input to reduce potential issues.

    @Echo Off
    Echo Rename a folder
    
    :OldName
    ClS
    Set "ON="
    Set /P "ON=Name of the folder to rename: "
    If Not "%ON%"=="" (If Exist "%ON%\" (GoTo NewName
        ) Else Echo The folder was not found)
    Echo Please try again!
    Pause
    GoTo OldName
    
    :NewName
    ClS
    Set "NN="
    Set /P "NN=New folder name: "
    If "%ON%"=="" GoTo NewName
    If Exist "%NN%\" (Echo The folder %NN% already exists
        Pause
        GoTo NewName) Else (Ren "%ON%" "%NN%" && (Echo %ON% has been renamed) || (
            Echo An error occurred renaming %ON%)
        Pause)
    

    You are asking for user input, and that user can put whatever they want into that input prompt. The only way to make this robust is to ensure that you fully cater for any possible input!