Archive script help

by jw1 at 2012-10-25 13:44:45

I lifted the following code from another board and made a couple of changes to it. The purpose of the script is to move files older than 400 days from source to destination, while maintaining the original path information. What I’ve run into is the folders, nested several layers deep are often over 400 days and are also being moved. I’m a complete noob to PowerShell and could use some help.

How might I step through the subfolders but only move files, maintaining the path of course. I just don’t want it moving the sub folder structure from the Records folder.

Thanks for any and all help.


$Source = "D:\Records"
$Destination ="D:\Archive"
$Past = (Get-Date).AddDays(-400)
$List = dir $Source -recurse | Where {$.CreationTime -lt $Past}
foreach($file in $list){
$MovePath = (join-path -path $Destination -childpath $file.FullName.SubString(3))
$MoveDirectory = (join-path -path $Destination -childpath $file.DirectoryName.SubString(3))
new-item -path $MoveDirectory -type directory -ea SilentlyContinue
move-item -Path $file.FullName -destination $MovePath
by DonJ at 2012-10-25 13:52:07
I don’t understand, sorry.

If the source file is C:\This\Path\Is\Really\Long\file.txt

You want it moved to:




To me, there seems to be a conflict between “maintaining the path” and “not moving the sub folder structure.” Give me a quick example of what the starting path for a file looks like, and what you want the end path to look like.
by jw1 at 2012-10-25 14:01:44
I would like to move the files only

Source C:\This\Path\Is\Really\Long\file.txt

Destination C:\Archive\This\Path\Is\Really\Long\File.txt

For instance, regardless of the date on the folder, I wish to maintain the folder in the current location.

If the date of any file in any subfolder of the source tree is less than 400 days old I with to move the file, replicating the directory structure and placing it within the destination folder.
by DonJ at 2012-10-25 14:15:36
AH. So what you REALLY want to do is just exclude folders, and only get files. In v3, that’s easy, because there’s a switch on Get-ChildItem (Dir) that will return only files. It’ll still recurse subfolders, just not list them.

In v2, you’d have to add a clause to your Where statement.

where { $
-is [System.IO.FileInfo] -and $_.CreationDate -lt $past }

That way, folders aren’t even considered for moving - only the files in them. The file itself has all of the information needed to construct the destination path, which it looks like is already happening.
by jw1 at 2012-10-26 12:49:06
Thanks for the assistance, I used your suggestion and learned a couple things along the way. Wish I had more time to delve into this scripting language, it looks very powerful.
by DonJ at 2012-10-26 12:55:31
Pick up Learn Windows PowerShell 3 in a Month of Lunches. An hour a day, during lunch, is all you need.