Excerpt

Thursday, November 10, 2016

Move files into folders, sorted by month and day with PowerShell

Notes:



  • Not suitable for folder with sub-folders, such as folder of extracted zip file

  • Recommended to execute on a test environment first


Steps:



  1. Change the $files and $targetPath values accordingly

  2. Copy the modified script and paste into Windows PowerShell

  3. Wait


The script:


# Get the files which should be moved, without folders
$files = Get-ChildItem 'CHANGE THIS TO ORIGINAL PATH' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
$files

# Target folder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'CHANGE THIS TO TARGET PATH'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()

# Out FileName, year and month
$file.Name
$year
$month

# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}

Screenshots:


[caption id="attachment_5100" align="aligncenter" width="646"]2016-11-09_11-51-24 Before (what a mess!)[/caption]

2016-11-09_11-58-42

2016-11-09_12-10-37

[caption id="attachment_5104" align="aligncenter" width="702"]2016-11-09_15-14-41 After[/caption]

2016-11-09_12-16-26

Source:


 

http://www.thomasmaurer.ch/2015/03/move-files-to-folder-sorted-by-year-and-month-with-powershell/

No comments:

Post a Comment