Search code examples
powershell

Create Daily Folder, Move Files Into it, then Move that Folder Into Achive Folder


I'm an IT Admin, but I don't know PowerShell. I created a script by googling online and playing with it, but I need a bit more functionality.

Here's a bit of background info: Every day we scan a bunch of documents into a folder called "Scans". Inside the "Scans" folder, there is also a folder called "Archive"

This is what I'm trying to accomplish with a script:

I would like the script to run every night. If there are any files (not folders) inside the "Scans" folder,

  • create a folder with current date as the folder name like this (08-30-2024)
  • move those files based on the created date to that folder for the current date
  • move that folder for the current date and the files inside it, into the "Archive" folder.

If there are no files on a particular day, then the script does nothing.

I hope this makes sense.

$datecurrent = get-date -Format MM-dd-yyyy
New-Item -ItemType directory -Path "C:\Users\Admin\Desktop\Scans\$datecurrent"

$DestinationFolder = "C:\Users\Admin\Desktop\Scans$datecurrent"
$archiveFolder = "C:\Users\Admin\Desktop\Scans\Archive"

$EarliestModifiedTime = get-date (get-date -format d)
$Files = Get-ChildItem "C:\Users\Admin\Desktop\Scans*.*"

foreach ($File in $Files) {
    if ($File.LastWriteTime -gt $EarliestModifiedTime) {
        Move-Item $File -Destination $DestinationFolder
        Write-Host "Copying $File"
    } else { 
        Write-Host "Not copying $File"
    }
}

Move-Item $DestinationFolder -Destination $ArchiveFolder

Solution

  • This should be all you need:

    $Root = 'C:\Users\Admin\Desktop\Scans'
    $ArchiveRoot = 'C:\Users\Admin\Desktop\Scans\Archive'
    
    $CurrentFileList = Get-ChildItem -Path $Root -File
    if ($CurrentFileList) {
        $DestinationFolder = Join-Path -Path $ArchiveRoot -ChildPath $(Get-Date -Format 'yyyy-MM-dd')
        New-Item -Path $DestinationFolder -ItemType Directory | Out-Null
        Move-Item -Path $CurrentFileList.FullName -Destination $DestinationFolder -Force
    }