PowerShell - 从特定文件夹复制特定文件

PowerShell - Copy specific files from specific folders

因此,文件夹结构如下所示:

  1. 源文件夹
    • file1.txt
    • file1.doc
      1. 子文件夹1
        • file2.txt
        • file2.doc
          1. 子子文件夹
            • file3.txt
            • doc3.txt

我想要做的是将所有 .txt 文件从文件夹(其(文件夹)名称包含 eng)复制到目标文件夹。只是文件夹中的所有文件 - 不是文件结构。

我用的是这个:

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

问题是它只从每个父文件夹而不是子文件夹复制 .txt 文件。

如何将所有子文件夹包含在此脚本中并同时保留 eng 名称检查?你能帮帮我吗?

我说的是 PowerShell 命令。我应该改用 robocopy 吗?

使用 powershell 很好。尝试:

$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 }

首先获取名称中包含 eng 的所有文件夹的列表可能更容易。

$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
}

又一个 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
        }

你可以这样做:

$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

再拍一张:

$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}