Vael Victus
Vael Victus

Reputation: 4122

How to delete a folder and move its contents to the parent in Powershell?

I have many packs of icons downloaded from a website whose downloads are structured as: pack/svg/icons, but this redundant structure is not ideal for my project. I just want to have my icons directly under the pack directory. So this is how it is now:

📂 Categorized Icons
  └📁 RandomCat1
      └📁 svg
          └ icon1.svg
          └ icon2.svg
   └📁 RandomCat2
      └📁 svg
          └ moreicons.svg
          └ alldifferentnames.svg

And how I want it:

📂 Categorized Icons
  └📁 RandomCat
      └ icon1.svg
      └ icon2.svg

The problem is that I don't know RandomCat's name, and I don't want to run this command for every possible folder. I need something like, "move all icons to ../, delete /svg/".

Upvotes: 0

Views: 1025

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

First enumerate all directories named "svg" under your base directory. The returned DirectoryInfo objects can be used for accessing the folder content. They also have a property Parent that references their parent folder object. Use the latter as the target for moving the former. Delete the source folder afterwards.

Get-ChildItem 'C:\folder' -Filter 'svg' -Directory -Recurse -Force | ForEach-Object {
    Move-Item "$($_.FullName)\*.svg" -Destination $_.Parent.FullName
    Remove-Item $_.FullName -Force
}

Note that in PowerShell versions prior to v3 Get-ChildItem doesn't have a parameter -Directory. If you're restricted to antiquated versions you need to use something like this for enumerating the "svg" folders:

Get-ChildItem 'C:\folder' -Filter 'svg' -Recurse -Force | Where-Object {
    $_.PSIsContainer
} | ...

Upvotes: 3

Related Questions