Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Copy specific files from specific folders

So, the folder structure looks like this:

  1. SourceFolder
    • file1.txt
    • file1.doc
      1. Subfolder1
        • file2.txt
        • file2.doc
          1. SubSubFolder
            • file3.txt
            • doc3.txt

What I want to do is copy all .txt files from folders, whose (folder) names contains the eng, to a destination folder. Just all the files inside the folder - not the file structure.

What I used is this:

$dest = "C:\Users\username\Desktop\Final"
$source = "C:\Users\username\Desktop\Test1"
Copy-Item $source\eng*\*.txt $dest -Recurse

The problem is that it copies the .txt files only from each parent folder but not the sub-folders.

How can I include all the sub-folders in this script and keep the eng name check as well? Can you please help me?

I am talking about PowerShell commands. Should I use robocopy instead?

like image 750
John Enxada Avatar asked Mar 17 '15 13:03

John Enxada


People also ask

Does xcopy work in PowerShell?

xcopy is the windows command. It works with both PowerShell and cmd as well because it is a system32 utility command.

How do I copy a folder and content in PowerShell?

Use Copy-Item Cmdlet to Copy Folder With Subfolders in PowerShell. The Copy-Item cmdlet copies an item from one location to another. You can use this cmdlet to copy the folder and its contents to the specified location. You will need to provide the source and destination path to copy from one place to another.


2 Answers

Yet another PowerShell solution :)

# Setup variables
$Dst = 'C:\Users\username\Desktop\Final'
$Src = 'C:\Users\username\Desktop\Test1'
$FolderName = 'eng*'
$FileType = '*.txt'

# Get list of 'eng*' file objects
Get-ChildItem -Path $Src -Filter $FolderName -Recurse -Force |
    # Those 'eng*' file objects should be folders
    Where-Object {$_.PSIsContainer} |
        # For each 'eng*' folder
        ForEach-Object {
        # Copy all '*.txt' files in it to the destination folder
            Copy-Item -Path (Join-Path -Path $_.FullName -ChildPath '\*') -Filter $FileType -Destination $Dst -Force
        }
like image 140
beatcracker Avatar answered Nov 15 '22 04:11

beatcracker


You can do this :

$dest = "C:\NewFolder"
$source = "C:\TestFolder"
$files = Get-ChildItem $source -File -include "*.txt" -Recurse | Where-Object { $_.DirectoryName -like "*eng*" }
Copy-Item -Path $files -Destination $dest
like image 31
Mathieu Buisson Avatar answered Nov 15 '22 02:11

Mathieu Buisson