PowerShell - copy specific files from specific folders

So, the folder structure looks like this:

  • 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 (folders) names contain eng to the destination folder. Just all the files inside the folder are not a file structure.

What I used:

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

The problem is that it only copies .txt files from each parent folder, but not subfolders.

How to include all subfolders in this script and save the eng name check? Can you help me?

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

+4
source share
5 answers

PowerShell:)

# 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
        }
+6

:

$SourceRoot = <Source folder path>
$TargetFolder = <Target folder path>


@(Get-ChildItem $SourceRoot -Recurse -File -Filter *.txt| Select -ExpandProperty Fullname) -like '*\eng*\*' |
foreach {Copy-Item $_ -Destination $TargetFolder}
+1

It's great to do this with powershell. Try:

$dest = "C:\Users\username\Desktop\Final"
$source = "C:\Users\username\Desktop\Test1"

Get-ChildItem $source -filter "*.txt" -Recurse | Where-Object { $_.DirectoryName -match "eng"} | ForEach-Object { Copy-Item $_.fullname $dest }
0
source

At first, it may be easier to get a list of all the folders that contain engthe name.

$dest = "C:\Users\username\Desktop\Final"
$source = "C:\Users\username\Desktop\Test1"

$engFolders = Get-ChildItem $source -Directory -Recurse | Where { $_.BaseName -match "^eng" }
Foreach ($folder In $engFolders) {
    Copy-Item ($folder.FullName + "\*.txt") $dest
}
0
source

You can do it:

$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
0
source

All Articles