0

I was curious to make such thing in windows cmd that is taking source.txt file with such names:

User1
User2
User3
User4
User5
User6

Secondly, I have created the destination folder F:\Destination The task is to iterate with source.txt and if a file from this txt exists at the address F:\Destination, delete it, if such file does not exist, create a folder with this name.

For example: I have User1.txt User2.txt and User3.txt in F:\Destination as a result I need to delete them and create folders User4 User5 and User6

Here is my script, but sadly it's doing nothing

for /F "usebackq eol=| delims=" %G in ("source.txt") do if exist
"Destination\%~G" del "Destination\%~G" if not exist "Destination\%~G" md "Destination\%~G"

Looking forward to your suggestions and solutions. Thanks!

1
  • Do you have a particular reason to use the commandline? With PowerShell it would be a simple to create those folders Get-Content .\source.txt | ForEach-Object { New-Item -Type Directory -Name $_ } adding the other logic might also be easier/more readable.
    – Seth
    Commented Sep 28, 2022 at 6:45

1 Answer 1

0

I see some issues:

  • The way to reference the G variable in a batch file is %%G, not %~G
  • You said that the files in the destination folder are named User1.txt etc, but you don't check for .txt
  • The options in the for command don't really do anything now, you can leave those out. In that case, do not quote source.txt. See help for for details
  • The line break between your two lines doesn't help, or is that just the formatting of your question? If so, please fix that. Anyway, it's better to format the code a bit, and use parentheses

Something like this should work:

for /F %%G in (source.txt) do (
    if exist "Destination\%%G.txt" del "Destination\%%G.txt" 
) else (
    if not exist "Destination\%%G" md "Destination\%%G"
)
2
  • This is somehow correct, but this script creating folder whenever .txt is listed in the F:\Destination or not. Anyway, thanks for helping. Commented Sep 28, 2022 at 8:15
  • Ah, I misread your question, fixed.
    – Berend
    Commented Sep 28, 2022 at 8:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .