Remove everything in the path except some files in Windows CMD

304 views Asked by At

When it comes to Windows command prompt, I always get confused about path, which seems so easy to grasp in Linux Terminal counterparts.

What I wanna do is, I want to delete everything(both files and folders in one command) in the path (for eg. pub\static directory path) except a file called .htaccess relative from my root directory(C:\wwwroot\Magento2), which is open in Windows command prompt.

How can I do this, I tried the below for loop, but it deletes .htaccess instead. Also how to avoid for loop altogether but get the job done as I described (relative from root directory) ?

for %i in (C:\wwwroot\Magento2\pub\static\*) do if not %i == .htaccess del %i

So I googled a bit and tried below one, but it doesn't do anything:

FOR /D %p IN ("C:\wwwroot\Magento2\pub\static\*.*") DO ( IF NOT %p == .htaccess ( IF EXIST %~sp\NUL ( RMDIR "%p" /S /Q ) ELSE ( DEL /F "%p" ) ) )
1

There are 1 answers

3
Bill_Stewart On

Single PowerShell command:

Get-ChildItem C:\inetpub\wwwroot\Magento2\pub\static -Recurse |
  Where-Object { $_.Name -ne ".htaccess" } | Remove-Item -Recurse