如何使用子文件夹复制文件夹?

gre*_*ine 17 powershell powershell-2.0 powershell-3.0

此脚本在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
}
Run Code Online (Sandbox Code Playgroud)

gve*_*vee 40

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-Itemcmdlet并指定–Container切换参数:

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

Copy-Item -Path $sourceRoot -Filter "*.txt" -Recurse -Destination $destinationRoot -Container
Run Code Online (Sandbox Code Playgroud)

  • 不,它确实有效.我添加了那个队友. (2认同)
  • 根据文档,`Container` 默认开启:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6#optional-parameters (2认同)