Search code examples
vbscriptbatch-filefile-renamebatch-rename

Toggle extensions via bat or vbs


I need to quickly toggle the extension of all files contained in a specific folder.

Suppose that C:\My Folder\ contains 200 files (all .txt).

BY EXECUTING THE SCRIPT I change them all to .xml

and then

BY EXECUTING THE SAME SCRIPT AGAIN I change them all back to .txt.

In other words executing this one script will indefinitely turn these 200 files (if they are .txt) to .xml and (if they are .xml) to .txt and loop...

For a batch I had in mind something like this (which does not work):

@echo off

IF EXIST "C:\My Folder\*.txt" GOTO RENAMETXT
IF NOT EXIST "C:\My Folder\*.txt" GOTO RENAMEXML

:RENAMETXT
ren "C:\My Folder\*.txt" "*.xml"

:RENAMEXML
ren "C:\My Folder\*.xml" "*.txt"

Solution

  • Your proposed batch script does not work because the :RENAMETXT portion falls through to :RENAMEXML. It could be fixed by simply inserting EXIT /B before :RENAMEXML.

    But there is no need for GOTO or EXIT /B - You can simply use IF ... ELSE ...

    @echo off
    if exist "C:\My Folder\*.txt" (
      ren "C:\My Folder\*.txt" *.xml
    ) else (
      ren "C:\My Folder\*.xml" *.txt
    )