サブフォルダを含むフォルダをコピーするにはどうすればいいですか? [重複] 質問する

サブフォルダを含むフォルダをコピーするにはどうすればいいですか? [重複] 質問する

このスクリプトは 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
}

ベストアンサー1

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–Containerスイッチされたパラメータを指定します。

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

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

おすすめ記事