FN_
FN_

Reputation: 853

Copy specific subfolder from multiple folders using Powershell

I am trying to do some Logs backup and struggle with ps1 command which can do this for me.

I have folder structure like this:

folder_root/
├── sub_a/
│   ├── Logs
│   ├── bootstrap.min.css
│   ├── Configuration
├── sub_b/
│   ├── Logs
│   └── Settings
└── sub_c/
    ├── Logs
    ├── Application
    ├── class.js
    └── other-file.html

And I need to extract only Logs folder from all subdirs and copy it into backup folder (which exists) respecting existing folder structure:

Backup-03-24/
├── sub_a/
│   └── Logs
├── sub_b/
│   └── Logs
└── sub_c/
    └── Logs

How to achieve this using Powershell? I am trying to use Copy-Item cmdlet with wildcard in path, but it does not work.

Copy-Item -Destination "C:\folder_root\*\Logs"

Upvotes: 0

Views: 358

Answers (1)

Theo
Theo

Reputation: 61028

This is'n too hard to do. Just loop over the directories you get with Get-ChildItem, using a filter for the name of the folders you want to copy:

$sourcePath  = 'D:\folder_root'
$Destination = 'D:\Backup-03-24'
Get-ChildItem -Path $sourcePath -Filter 'Logs' -Recurse -Directory |
    ForEach-Object {
        $targetPath = Join-Path -Path $Destination -ChildPath $_.Parent.FullName.Substring($sourcePath.Length)
        $null = New-Item -Path $targetPath -ItemType Directory -Force
        $_ | Copy-Item -Destination $targetPath -Recurse -Force
    }

Result:

D:\BACKUP-03-24
+---sub_a
|   \---Logs
+---sub_b
|   \---Logs
\---sub_c
    \---Logs

Upvotes: 2

Related Questions