U bent hier

PowerShell script to archive files into sub-directories

This script is written to process files being placed by other processes in subfolder 'log' and 'archive' of subfolders in the folder d:\mainfolder\

So if a structure like this exists:

d:\mainfolder
d:\mainfolder\A
d:\mainfolder\A\log
d:\mainfolder\A\archive
d:\mainfolder\B
d:\mainfolder\B\log
d:\mainfolder\B\archive
 

Then this script will go through the four folders ..A\log, ..A\archive, ..B\log, ..B\archive and move files found there in sub-folders underlaying these sub-folders with structure log[yyymm] or archive[yyymm]

The code:

#Configuration
$rootfolder = "d:\mainfolder"
$subfolders = @("log", "archive")

#Run for each plant
$plants = get-childitem -path $rootfolder | where { $_.PSIsContainer }
foreach ($plant In $plants) {

    foreach ($subfolder In $subfolders) {

        $folder = $plant.FullName + "\" + $subfolder
        $files = get-childitem -path $folder | where { -not $_.PSIsContainer }
        
        if ($files) {

            $feedback = " Folder " + $folder + ":"
            echo $feedback

            foreach ($file In $files) {
                $newFolder = $folder + "\" + $subfolder + $file.lastwritetime.tostring("yyyyMM") + "\"
                $newName = $newFolder + $file.name
                $feedback =  "   Archived to " + $newName
                echo $feedback
                If (-Not {Test-Path $newFolder -pathType container}) {
                      New-Item -ItemType Directory -Force -Path $newFolder
                }
                Move-Item -path $file.Fullname -Destination $newName -force
            }
        } else {
            $feedback = " Folder " + $folder + ": no files to process"
            echo $feedback
        }
    }

}