使用Powershell将所有文件夹和子文件夹从一个驱动器移动到另一个驱动器

时间:2015-05-28 06:48:33

标签: windows powershell

我使用Powershell脚本将文件夹从一个驱动器移动到另一个驱动器。

这是我尝试过的。

Get-ChildItem -Recurse "C:\Personal"  | where-object {$_.lastwritetime -gt '5-25-2015'} | foreach {move-item "$($_.FullName)" "D:\Personal"}

如果我在同一个驱动器中移动文件,即从cdrive到c驱动器或d驱动器到d驱动器,这是有效的。 但是当我试图从c盘转移到d盘时,这不起作用,......我得到的错误就像

Move-Item : The file exists.
At line:1 char:113
+ Get-ChildItem -Recurse "C:\Development"  | where-object {($_.lastwritetime -lt (get-date))} | foreach {move-item <<<<
"$($_.FullName)" "D:\Development1"}
+ CategoryInfo          : WriteError: (C:\Development\test3.txt:FileInfo)  [Move-Item], IOException
 + FullyQualifiedErrorId :  MoveFileInfoItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand

请纠正我..

1 个答案:

答案 0 :(得分:2)

什么意思&#34;这不起作用&#34;?

recurse标志似乎表示您要复制目录结构。这仅在目标目录与源具有相同结构时才有效。如果没有,你必须沿途创建它。像这样的东西会起作用:

function Move-Directories 
{
    param (
        [parameter(Mandatory = $true)] [string] $source,
        [parameter(Mandatory = $true)] [string] $destination        
    )

    try
    {
        Get-ChildItem -Path $source -Recurse -Force |
            Where-Object { $_.psIsContainer } |
            ForEach-Object { $_.FullName -replace [regex]::Escape($source), $destination } |
            ForEach-Object { $null = New-Item -ItemType Container -Path $_ }

        Get-ChildItem -Path $source -Recurse -Force |
            Where-Object {  (-not $_.psIsContainer) -and ($_.lastwritetime -ge (get-date)) } |
            Move-Item -Force -Destination { $_.FullName -replace [regex]::Escape($source), $destination }
    }

    catch
    {
        Write-Host "$($MyInvocation.InvocationName): $_"
    }
}

通过这样的电话:

Move-Directories "c:\personal" "d:\personal"