Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell script to move files into year/month folders based on creation timestamp

Tags:

powershell

First post here...I apologize if this isnt formatted correctly...I will work on this. I am working on a Powershell script that will get me the following information so that I can work with another batch file that works perfectly to this point. As I grow in my understanding of Powershell...I will most likely change the batch file since it is pretty lengthy.

TL:DR Newb working with Powershell needs help

I am wanting Powershell to output a single line of information for each file in a folder excluding any subfolders. I would like my txt file to look like this:

file creation date_full path to filename

one file per line. This will be parsed into a text file later

Here is what I have so far...seems like I just need a for loop to run something like this psuedocode and I should be good to go. Any help would be appreciated at this point.

Thanks all and I hope I am not killin you with formatting.

$USS_Folder="path\USS_Files\"
$uss_year=#4 digit year of file creation date
$uss_month=#2 digit year of file creation date
$uss_file=# Full filename including path and Creation_Date

New-Item -ItemType directory -Path $USS_Folder\$uss_year\$uss_month

Move-Item $uss_file $USS_Folder\$uss_year\$uss_month
like image 271
Joshua Avatar asked Dec 25 '22 15:12

Joshua


1 Answers

So after spending a while pouring over a number of pages filled with scripts, I came up with this solution below and modified to fit my needs. I have it employed into production and it works great.

Adapted from PowerShell: Moving files into subfolder based on date

<#
Set Variables of Source folder and Destination folder
Assign variable of files to be the files with uss extension
For each file with uss extension assign the Directory variable the information for file creation year and month
    if the year and month folder do not exist, then create them from file creation information
Move file to sub-folder of year and month from file creation information passed into Directory variable
#>

$SourceDir = "path to uss files\USS_Files\"
$DestinationDir = "path to uss files\USS_Files\"

$files = get-childitem $SourceDir *.uss

foreach ($file in $files) 
{
    $Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString('yyyy') + "\" + $file.CreationTime.Date.ToString('MM-MMM')

    if (!(Test-Path $Directory))
    {
        New-Item $directory -type directory
    }
    Move-Item $file.fullname $Directory 
}
like image 171
Joshua Avatar answered Jan 19 '23 01:01

Joshua