1

I've never used batch programming before, my experience is with Java and C#, but I wanted to try to learn. I am trying to make a script so that when I run it, I put in a directory path, and then the program will go through every file in said folder, tell me the name of it and ask if I want to delete it. This is what I have so far:

@ECHO off
set /p folder="Folder Address: "
FOR /R %folder% %%G IN (.) DO (
    set filepath=%%~dpa
    set /p delete="Delete?: "
    IF %delete%="Y" IF %delete%="y"(
    del %filepath%
    )

    pause
)

So when I start the script, it asks for the folder address. I type in C:\Users\Tim\Downloads and press Enter. Then, the command prompt closes and nothing happens. I've been looking into the FOR loop syntax and whatnot, but I still can't find what I'm doing wrong. Any help would be appreciated, thanks!

Edit: I'm pretty sure there are differences in syntax between operating systems. So just in case it's important, I have Windows 7.

Edit: I have updated the code to what npocmaka suggested:

@ECHO off
set /p folder="Folder Address: "
FOR /R %folder% %%G IN (.) DO (
    set filepath=%%~dpa
    set /p delete="Delete?: "
    IF /I !delete!="Y"(
      del !filepath!
    )

    pause
)

It still yields the same results, however.

1
  • You can use the tree command. <br> Example: tree D:\ Commented Sep 14, 2015 at 22:47

1 Answer 1

1

You need delayed expansion and proper OR logic (the one you are using is rather AND - use the /I switch in IF ):

   @ECHO off
set /p folder="Folder Address: "
setlocal enableDelayedExpansion
FOR /R "%folder%" %%G IN (*) DO (
    set "filepath=%%~fG"
    set /p delete="Delete !filepath!?: "
    IF /I "!delete!" equ "Y" (
       del /Q "!filepath!"
    )

    rem pause
)
Sign up to request clarification or add additional context in comments.

6 Comments

Are you purposely using exclamation marks at !delete! and !filepath!? Is that correct or did you mean to use %'s? Sorry, you can see how new I am to this haha
@Tim - when the delayed expansion is turned on you can access both ! and % to expand the variables.But with with ! variables are expanded when the command is executed and % when the command is parsed.So ! expands the variable a little bit later - in this case after the code block is parsed.
Alright, cool. It still is doing nothing though. Could I be entering the address wrong when I run it? I type it exactly as C:\Users\Tim\Downloads
@Tim - aah.%folder% should be quoted.Edited now
@Tim And with FOR /R you need wild card to display files correctly.Also fixed
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.