powershellsubdirectorydatecreated

Fild all xls files in subdirectories and move them to a folder based on file creation date


I have a folder that contains subfolders each with many excel spreadsheet. I am trying to get powershell to search through the subdirectories then move all the xls file with the same creation date into a new folder of that creation date. I am close I think here is my code. What is happening is that it only looks at file in "reporting" and not the subfolders of "reporting".

Get-ChildItem "c:\users\username\documents\reporting\*.xls" -Recurse | foreach {
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -Format yyyy.MM.dd
$des_path = "c:\users\username\documents\$new_folder_name"

if (test-path $des_path){
   move-item $_.fullname $des_path
   } else {
   new-item -ItemType directory -Path $des_path
   move-item $_.fullname $des_path
   }
}

Solution

  • There is no need to first use ToShortDateString() on the LastWriteTime property and then use that to recreate the date in order to format it.

    Because you are using the -Recurse switch to search subfolders aswell, the code can be adjusted to also the -Include parameter like:

    $sourcePath = 'c:\users\username\documents\reporting'
    $targetPath = 'c:\users\username\documents'
    Get-ChildItem $sourcePath -Include '*.xls', '*.xlsx' -File -Recurse | ForEach-Object {
        $des_path = Join-Path -Path $targetPath -ChildPath ('{0:yyyy.MM.dd}' -f $_.LastWriteTime)
        if (!(Test-Path -Path $des_path -PathType Container)) {
            # if the destination folder does not exist, create it
            $null = New-Item -Path $des_path -ItemType Directory
        }
        $_ | Move-Item -Destination $des_path -Force -WhatIf
    }
    

    The -WhatIf switch at the end of the Move-Item is for testing. Once you are satisfied with the text shown in the consoe, remove that switch to actually start moving the files.