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

标签 windows powershell

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

这是我尝试过的。

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

如果我在同一个驱动器内移动文件,即从 c 驱动器到 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

请纠正我..

最佳答案

“这不起作用”是什么意思?

递归标志似乎表明您要复制目录结构。这仅在您的目标目录已经具有与源目录相同的结构时才有效。如果没有,您必须一路创建它。这样的事情会起作用:

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"

关于windows - 使用 Powershell 将所有文件夹和子文件夹从一个驱动器移动到另一个驱动器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30499129/

相关文章:

c# - 如何使用 C# SendKeys 以编程方式按下 Windows 键

windows - 如何使用 Windows API 调用平滑地调整图像大小(通过重采样)?

windows - TLS1.2 Powershell HttpWebClient 支持

PowerShell 命令在文件名的特定位置添加字符

powershell - 使用 Start-Process 保留环境变量

windows - 使用全屏 OpenGL 应用程序时是否可以保持 Windows 的合成器正常工作?

linux - mac osx 在 sd 卡上显示胖分区,而 windows 不-为什么?

powershell - 具有大型包的 Set-AzureVMDscExtension 会导致 PowerShell DSC 扩展中的内存使用量极大

powershell - PowerShell 在哪里获取它放在此处字符串中的换行符?

c# - 如何在 Windows 11 中找到 Windows 产品名称?