Copying files and creating new folders based on “creationdate”

吃可爱长大的小学妹 提交于 2019-12-23 20:50:35

问题


I am counting all files in my Pictures folder with

Get-ChildItem C:\pictures -force | Group-Object extension | Sort-Object count -descending | ft count,name -auto

I am then copying all my MTS-files (video) to a separate folder with

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

This works nicely. But, how can I create a folder for each year in c:\video and then copy the corresponding files?

UPDATE:

Shay has helped me with accomplishing this and I now have the following code:

# 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"
        }
}    

It tests the folders OK, but skips all the Test-Path on files. Am I breaking the loop somehow? Or messing up the pipeline?


回答1:


Try this:

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
}


来源:https://stackoverflow.com/questions/11777466/copying-files-and-creating-new-folders-based-on-creationdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!