0
votes

I need some assistance with powershell - I would like to search within all subfolders of a particular folder, and copy the latest file from each subfolder to a new folder every day at 9.00 AM. So, I want to search within folder A's subfolder a, b and c to pick out the latest file in a, b and c each, and move all three files into outside folder B (a single folder). I am new to PowerShell - any help is appreciated. I've basically tried to use this but it creates a backup: Copy most recent file from folder to destination

Clear-Host
$ChildFolders = @('In_a', 'In_b', 'In_c')

for($i = 0; $i -lt $ChildFolders.Count; $i++){

$FolderPath = "C:\FolderA\" + $ChildFolders[$i]
$DestinationPath = "C:\FolderB\" [$i]

gci -Path $FolderPath -File | Sort-Object -Property LastWriteTime -Descending | Select FullName -First 1 | %($_){ 
$_.FullName
Copy-Item $_.FullName -Destination $DestinationPath 
}
1
will any of the files have the same name? Becuase it could overwrite another fileArcSet
No, all individually namedSam109

1 Answers

0
votes

Gets subfolders

Gets all files in subfolders

Sorts files by Creation Date into a array

Gets first Entry

Moves file to Destination directory

*It will overwrite files with the same name in the destination folder

Function Get-LatestFiles($SourceFolder,$Destination){
    $Subfolders = Get-ChildItem $SourceFolder -Directory
    [System.Collections.ArrayList]$SubFoldersExpanded = new-object System.Collections.ArrayList
    Foreach($SubFolder in $SubFolders){
        $SubFolderExpanded =  $Subfolder | %{(Get-ChildItem $_.FullName -File -Depth 1 | Sort-Object -Property CreationTime -Descending)}
        if($SubFolderExpanded.Count -gt 0){
            $SubFolderExpanded[0] | %{Move-Item $_.FullName -Destination $Destination -force}
        }
    }
}
Get-LatestFiles -SourceFolder C:\test -Destination C:\test01