如何从文件夹复制文件以及powershell脚本中的子文件夹中的文件

how to copy files from a folder and also files in sub folder in powershell script

如何使用 powershell 脚本从文件夹及其子文件夹中复制 .txt 类型的文件。如果文件是我的子文件夹,我希望将子文件夹也复制到目标位置。谢谢

我尝试了以下方法

Copy-item c:\tes\* *.txt c:\dest -recurse -force

这只会复制根文件夹中的文件,而不是子文件夹中的文件。

这可能不是最佳解决方案,但应该可行:

我使用 Get-ChildItem cmdlet to filter all *.txtfiles, determine the new path, creating the new directory using md and finally copy the files using the Copy-Item cmdlet:

$source = 'D:\test1'
$destination = 'D:\test2'

Get-ChildItem -Path $source -Filter *.txt -Recurse | % {
 $newDirectory = Join-Path $destination ($_.DirectoryName.Substring($source.Length))
  md $newDirectory -Force | out-null
  Copy-Item $_.FullName -Destination $newDirectory
 }