0

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"
1

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.