Search code examples
cmdwindows-server-2012

if exist folder rmdir folder && mkdir folder will not execute any command after that &&


What is the syntax that would allow me to delete folder and the create it, regardless of it prior (in)existence?

if exist folder rmdir folder && mkdir folder

Will NOT work. Neither replacing && with &, ||, |...

Which is proper syntax then?

OS: Windows 2012 Shell: cmd.exe*

PS I could accept PS based answers as long as two conditions are met. 1) It have to start from cmd.exe 2) It have to give meaningufull errors to cmd standard output if there are any encountered (like lack of permissions).


Solution

  • Since you are using rmdir without the /S switch I assume the folder of interest is empty, so why removing and recreating it? You could simply create it and suppress the error message in case it already exists, like:

    mkdir "folder" 2> nul
    

    This variant maintains all folder attributes and the owner, of course.


    If you insist on removing and recreating the folder, use this:

    rmdir "folder" 2> nul & mkdir "folder"
    

    This variant destroys all folder attributes and the owner.


    In case the folder is not guaranteed to be empty, you need the /S switch for rmdir; also the /Q is useful to avoid being prompted to really remove the folder, like:

    rmdir /S /Q "folder" & mkdir "folder"