1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PowerShell Move-Item フォルダ上書き対応

Last updated at Posted at 2021-03-01

PowerShell で Move-Item でフォルダ上書きがエラーになってしまう。
-Force 使ってもファイルの上書きはできるがフォルダはエラーになる。。。

対応としては以下のように考えてみた。
今のところ機能してるので大丈夫そう。。。

$path = "C:\test1";
$dist = "C:\test2";

# 以下の Move だと test1, test2 に同名のフォルダがあるとエラーになってしまう。。。
# Move-Item $($path + "\*") -Destination $dist -Force;

# ChildItem でループ
Get-ChildItem $path | ForEach-Object {
    # Move-Item を行う function として moveItem 作成して呼び出す
    moveItem $_.FullName $($dist + "\" + $_.Name);
} 

############ moveItem
function moveItem($path, $dist) {
    if ((Test-Path $dist) -and (Test-Path -PathType Container $path)) {
        # フォルダ上書き(移動先に存在 かつ フォルダ)は再帰的に moveItem 呼び出し
        Get-ChildItem $path | ForEach-Object {
            moveItem $_.FullName $($dist + "\" + $_.Name);
        }
        # 移動し終わったフォルダを削除
        Remove-Item $path -Recurse -Force;  
        Move-Item $path -Destination $dist -Force;
    } else {
        # 移動先に対象なし または ファイルの Move-Item に -Forece つけて実行
        Move-Item $path -Destination $dist -Force;
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?