Search code examples
batch-filelines

avoid long lines of code in batch file


Should be an easy one. I have made a batch that works but I think it contains overly long sentences. I had to play around with brackets but very quickly realized I didn't understand what I was doing. Any tips would be excellent.

Here is the code

IF "%deletetype%" == "prompt" (for /d /r "C:\Users" %%a in (*Folder*) do if exist "%%a" rmdir /s "%%a") ELSE (for /d /r "C:\Users" %%a in (*Folder*) do if exist "%%a" rmdir /s /q "%%a")
IF "%deletetype%" == "prompt" (for /d /r "C:\Documents and Settings" %%a in (*Folder*) do if exist "%%a" rmdir /s "%%a") ELSE (for /d /r "C:\Documents and Settings" %%a in (*Folder*) do if exist "%%a" rmdir /s /q "%%a")

As you can see it seems too long and as soon as I move ELSE anywhere or bracket it, the code breaks and I'm stuck. What could I do to break it up into smaller chunks. Thank you!

Thanks for all help here. I was wondering if I could apply this to other sentences that could do with shortening too. I tried with the line below but I'm out of my depth again. I wonder if you cant do that using the || (run if fail) && (run on success) characters? Maybe use a different conditioner?

msiexec.exe /norestart /qn /x {3EBE26E0-8630-4351-B18F-06AB4067AC49} || Echo Driver Already Removed or Not Exist! && (pause) && If "%drvtype%" == "grundig" (goto drivers)

managed to do it with this...Thanks!!

msiexec.exe /norestart /qn /x {07A1C1F1-52A2-49F4-A413-FF9A4FC3EDB6} || ( 
Echo   Olympus Driver Already Removed or Not Exist! Press Space Bar to Continue 
) && pause>nul && (If "%drvtype%" == "olympus" (goto drivers) 
    )
)

Solution

  • You could write your script like this:

    IF "%deletetype%" == "prompt" (
        for /d /r "C:\test" %%a in (*Folder*) do (
            if exist "%%a" rmdir /s "%%a"
        )
    ) ELSE (
        for /d /r "C:\test" %%a in (*Folder*) do (
            if exist "%%a" rmdir /s /q "%%a"
        )
    )
    

    The key for this to work for the if-else statement is to have ELSE on the same row as the closing parenthesis for the IF.