mino
mino

Reputation: 135

Powershell , remove folder with the same name like .zip

I must delete files which have been extracted from a zip file, into a folder named after the zip file, i.e.:

\test1.zip -> \test1

My script must find the folder which have the same name as the zip file and delete this folder.

Upvotes: 0

Views: 1273

Answers (1)

Richard Slater
Richard Slater

Reputation: 6378

Get a list of all of the Zip files in the directory, then loop over the results and delete any folder with the same name minus the extension, also known as the BaseName.

Get-ChildItem -Filter *.zip | `
  ForEach-Object { if (Test-Path $_.BaseName) {
    Remove-Item -Recurse -Force $_.BaseName }
  }

You can enter the entire command on one line, I have split it up so that it is easy to read on here. I used the following commands in this example:

  • Get-ChildItem - Creates a object in the pipeline for each file with a .zip extension
  • ForEach-Object - Simply allows you to perform an action for each object in the pipeline.
  • Remove-Item - note the use of -Recurse and -Force ensures that the folder is removed even if it contains files, you will not be asked to confirm.

Upvotes: 1

Related Questions