Search code examples
windowspowershellforeachscriptingcopy-item

Copy-item in foreach loop based off metadata


In this script I identify the metadata for a group of pictures, then run an if statement inside a foreach loop to copy all pictures from one folder with a certain date to a new directory with that date.

My problem is with Copy-Item, or so I think. If I use the variable $file$ it just places another directory inside the previous directory. The way I have it no just copies all the pictures into that directory despite the if statement that it is contained in.

$fol = "C:"

foreach ($file in $fol) {

    $data1 = Get-FileMetaData "C:"
    $data2 = $data1 | Select-Object 'Date taken'

    if ($data2 -like '*2006*') {

        if(!(Test-Path "C:\2006")) {
            New-Item -ItemType Directory -Path "C:\2006"
        }

        Copy-Item  "C:\*" "C:\2006"         
        echo $data2
    } else {
        echo 'no'
    }
}

echo $data2 displays:

return


Solution

  • why use metatdata for found creation date. You can use creationtime

    try this

    #if you want move for specific year
    $destination="c:\destination\2016"
    New-Item -ItemType Directory $destination -Force
    Get-ChildItem "c:\temp\" -Recurse -File -Filter "*.png" | Where {$_.CreationTime.Year -eq 2016} | %{Copy-Item $_.FullName "$destination\$($_.Name)" }
    
    #if you want copy all image png by year of creation
    $destination="c:\destination"
    
    Get-ChildItem "c:\temp\" -Recurse -File -Filter "*.png" | group {$_.CreationTime.Year} | 
    %{
    $DirYear="$destination\$($_.Name)"
    New-Item -ItemType Directory $DirYear -Force
    $_.Group | %{Copy-Item $_.FullName "$DirYear\$($_.Name)" }
    }