如何使用PowerShell将文件夹从一个位置移动到另一位置

时间:2018-11-12 14:56:47

标签: powershell

因此,我的目录充满了要移到另一个区域的文件夹,我也只想移动30天或更早之前创建的文件夹。我有一个脚本可以执行我对文件的需要,但它似乎不适用于文件夹。脚本在下面

用于移动文件的脚本

 param (
    [Parameter(Mandatory=$true)][string]$destinationRoot
 )

$path = (Get-Item -Path ".\").FullName

Get-ChildItem -Recurse | ?{ $_.PSIsContainer }
Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
Foreach-Object {
    $content = $path + "\" + $_.Name

    $year = (Get-Item $content).LastWriteTime.year.ToString()
    $monthNumber = (Get-Item $content).LastWriteTime.month
    $month = (Get-Culture).DateTimeFormat.GetMonthName($monthNumber)

    $destination = $destinationRoot + "\" + $year + "\" + $month 

    New-Item -ItemType Directory -Force -Path $destination

    Move-Item -Path $content -Destination $destination -force

}

Get-ChildItem部分似乎没有像应该那样拉目录。

1 个答案:

答案 0 :(得分:1)

因此,我看了看脚本后决定对某些内容进行修改

Function Move-FilesByAge(){
    param (
        [Parameter(Mandatory=$true)][string]$Source,
        [Parameter(Mandatory=$true)][string]$Destination,
        [Parameter(Mandatory=$true)][timespan]$AgeLimit
     )

    Get-ChildItem $Source -Directory -Recurse | ?{
        $($_.CreationTimeUtc.Add($AgeLimit)) -lt $((Get-Date).ToUniversalTime())
    } | %{
        $Dpath = $Destination + "\" + $_.CreationTimeUtc.ToString("yyyy") + "\" + $_.CreationTimeUtc.ToString("MMMM")
        New-Item -ItemType Directory -Force -Path $Dpath
        Move-Item $_ -Destination $Dpath -Force
    }
}

Move-FilesByAge -Source C:\Test -Destination C:\Test2 -AgeLimit (New-TimeSpan -days 30)

这可能会导致重大问题。如果存在相同名称的文件夹,则会弹出一个错误消息,指出该文件夹存在。

由于您是PowerShell的新手,所以让我们回顾一下有关此脚本的一些基础知识。在Powershell中,我们喜欢管道|,您在原始管道中做得很好。我们也非常喜欢别名Where-Object ?{},Foreach-Object %{}

Get-ChildItem具有一个内置的开关,仅用于返回目录-directory

当您应该使用 CreationTime 时,您还将使用最后一个 LastWriteTime CreationTimeUtc 允许您通过提供基本时区来标准化跨时区的时间。

Date.ToString(此处为日期格式)。是缩短日期解析为字符串的一种好方法。 .ToString("yyyy")会以4个数字(如2018年)为您提供年份。.ToString("MMMM")将以三月的名称来获取月份。