【问题标题】:Copying files and creating new folders based on "creationdate"根据“creationdate”复制文件和创建新文件夹
【发布时间】:2012-08-02 12:29:37
【问题描述】:

我用

计算“我的图片”文件夹中的所有文件
Get-ChildItem C:\pictures -force | Group-Object extension | Sort-Object count -descending | ft count,name -auto

然后我将我所有的 MTS 文件(视频)复制到一个单独的文件夹中

Get-ChildItem C:\pictures -force -recurse -include *.MTS | Copy-Item -Destination c:\video

这很好用。但是,如何在c:\video 中为每一年创建一个文件夹,然后复制相应的文件?

更新:

Shay 帮助我完成了这项工作,我现在拥有以下代码:

# Create a folder for each year and move the specified files to the corresponding folders
Get-ChildItem $fromFolder -Force | 
Group-Object {$_.CreationTime.Year} | Foreach-Object {

    # Testing to see if the folder exist
    if(!(Test-Path $toFolder\$($_.Name))) { 
        $folder = New-Item -Path "$toFolder\$($_.Name)" Itemtype Directory -Force 
        echo "Created $toFolder\$($_.Name)"
    } else {
        echo "Folder $toFolder\$($_.Name) exist"
    }

    # Testing to see if the file exist in the target directory
    if(!(Test-Path $_.group)) { 
        $_.group | Copy-Item -Destination $folder.FullName
        echo "Copyied $_ to $folder"
        } else {
            echo "File exist"
        }
}    

它测试文件夹正常,但跳过文件上的所有Test-Path。 我是否以某种方式打破了循环?还是弄乱了管道?

【问题讨论】:

    标签: powershell get-childitem copy-item


    【解决方案1】:

    试试这个:

    Get-ChildItem C:\pictures -Filter *.MTS -Force -Recurse | 
    Group-Object {$_.CreationTime.Year} | Foreach-Object{
        $folder = New-Item -Path "c:\video\$($_.Name)" ItemType Directory -Force
        $_.Group | Where-Object { -not (Test-Path "$($folder.FullName)\$($_.Name)") } | Copy-Item -Destination $folder.FullName
    }
    

    【讨论】:

    • 非常感谢谢伊!这行得通!但是我想复制,而不是移动:) 我也在尝试测试文件夹或文件是否已经被移动(我会不时运行这个脚本。)。我已经用我的代码更新了我的问题。再次感谢谢伊:)
    • 要复制文件,请将 Move-Item 替换为 Copy-Item。我更新代码。我还添加了一个 Where-Object,它只传递(通过文件名测试)目标路径上不存在的文件。
    • 非常感谢!极好的! (我知道复制项,我只是想一次比你更了解;)我的脚本正在扫描超过 100GB 的数据,我试图显示某种状态,但我对脚本的运行方式感到困惑。 .它是否扫描所有目录,然后将结果传递到管道并foreach-ing每个对象?我将如何制作正确的屏幕状态?再次感谢 Shay,您是我学习 Powershell 方面最好的老师之一:)
    • 它递归地扫描 C:\pictures 下的所有目录,按对象创建的年份对对象进行分组,然后将每个组成员通过管道传送到 foreach-object cmdlet(一次处理一个)。要输出状态消息,请在 foreach-object 脚本块内添加 Write-Host 行。
    猜你喜欢
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多