2017-05-09 173 views
2

此脚本在PowerShell中完美工作。它复制具有特定类型的所有文件。但我想复制文件与它的文件夹&子文件夹。如何复制文件夹与子文件夹?

$dest = "C:\example" 
$files = Get-ChildItem -Path "C:\example" -Filter "*.msg" -Recurse 

foreach ($file in $files) { 
    $file_path = Join-Path -Path $dest -ChildPath $file.Name 

    $i = 1 

    while (Test-Path -Path $file_path) { 
     $i++ 
     $file_path = Join-Path -Path $dest -ChildPath 
     "$($file.BaseName)_$($i)$($file.Extension)" 
    } 

    Copy-Item -Path $file.FullName -Destination $file_path 
} 
+0

请解释更多的细节,你想什么功能都有。一些实际的例子将是一个好的开始。 – vonPryz

+0

嗨,例如,文件夹中有1000个.txt文件。这会成功复制该文件,但不包含包含该文件的文件夹。 –

+0

简而言之,它不复制文件夹,而是复制文件。 –

回答

14

PowerTip:使用PowerShell来复制项目和保留文件夹结构

来源:https://blogs.technet.microsoft.com/heyscriptingguy/2013/07/04/powertip-use-powershell-to-copy-items-and-retain-folder-structure/

问:我如何使用Windows PowerShell 3.0的文件夹结构从一个驱动器复制到网络共享,并保留原有结构?

答:使用Copy-Item cmdlet,并指定–Container切换参数:

$sourceRoot = "C:\temp" 
$destinationRoot = "C:\n" 

Copy-Item -Path $sourceRoot -Filter "*.txt" -Recurse -Destination $destinationRoot -Container 
+0

你可以编辑我的代码添加它请欢呼 –

+0

$ dest =“C:\ n” Copy-Item -Path $ sourceRoot -Filter“* .txt”-Recurse -Destination $ destinationRoot -Container $ files = Get- ChildItem -Path “C:\管理支持” 筛选器 “*。味精” -Recurse 的ForEach($文件$文件){ $ FILE_PATH =联接路径-Path $ DEST -ChildPath $ file.Name $ I = 1 虽然(测试的路径-Path $ FILE_PATH){ $ I ++ $ FILE_PATH =联接路径-Path $ DEST -ChildPath“$($ file.BaseName)_ $($ I) $($ file.Extensio N)” } 拷贝项目-Path $ file.FullName -Destination $ FILE_PATH } –

+0

没有它的工作。我已添加该队友。 –

相关问题