1
I have files that constantly get pulled down from an ftp site into a directory.
They are all named in this format: yyyyMMdd_file1.txt
20160612_file1.txt
20161225_file2.txt
I am trying to move files with a creation date of 45 days and older to its own folder based on the basename's date. So, when the code is run, it should take the 20160612_file1.txt
and automatically create and move the file into a folder called 20160612
, but do nothing with the other file.
Get-ChildItem \\myfilepath | Where-Object {!$_.PSIsContainer -and $_.CreationTime.Date -lt (Get-Date).AddDays(-45)} | Foreach-Object{
$dest = Join-Path $_.DirectoryName $_.BaseName.Split('\_')[0]
if(!(Test-Path -Path $dest -PathType Container))
{
$null = md $dest
}
$_ | Move-Item -Destination $dest -Force
}
I just cannot seem to get the date comparison to work correctly. Any thoughts?
A bit more info:
The script above returns an error. Specifically:
PS C:\temp4> .\movefiles.ps1
At C:\temp4\movefiles.ps1:1 char:126
+ ... Object {!$_.PSIsContainer -and $_.CreationTime.AddDays(0) -lt Get-Dat ...
+ ~
You must provide a value expression following the '-lt' operator.
At C:\temp4\movefiles.ps1:1 char:127
+ ... ontainer -and $_.CreationTime.AddDays(0) -lt Get-Date.AddDays(-45)} | ...
+ ~~~~~~~~~~~~~~~~
Unexpected token 'Get-Date.AddDays' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : ExpectedValueExpression
It seems as though maybe I cannot compare the CreationTime.Date and (get-Date).AddDays(-45) values.
WORKING BELOW
$archivedate = (Get-Date).AddDays(-45)
Get-ChildItem \\filepath | Where-Object {!$_.PSIsContainer -and ($_.LastWriteTime -lt $archivedate)} | Foreach-Object{
$dest = Join-Path $_.DirectoryName $_.BaseName.Split('_')[0]
if(!(Test-Path -Path $dest -PathType Container))
{
md $dest
}
$_ | Move-Item -Destination $dest -Force
}
Does the filename itself always contain the date and as such, can that part of the file be used to move it accordingly, or is it required to check the creation date of the file itself? – LPChip – 2017-01-03T20:10:11.960
I suppose either way. I wanted it to based on creation date so I could apply it to other situations in the future. (ie, if the files did not start with a date) But, for this specific case, yes, the files always are prefixed with the creation date. – Narzard – 2017-01-03T20:16:21.407
Do you have more details on what results are you getting from this script? – uSlackr – 2017-01-03T21:48:51.520
@uSlackr just added the output I am getting. I am not sure how to make the two dates (fileCreation and dateTime::now-45 days) to be able to be compared. – Narzard – 2017-01-03T22:04:24.400