简体   繁体   中英

Powershell move files older than x match on date in filename

So I have a process that brings in a bunch of files from FTP server. I would like to move the files that are older than one month into the archive folder. However, if the files get overwritten,using LastWriteTime is probably not going to be accurate. Luckily the original date is stored in the file name.

#move files older than 1 month to archive
$archive = "\\fhnsrv01\home\aborgetti\Documentation\Stage\archive"
$date = (get-date).AddDays(-31)
GCI \\fhnsrv01\home\aborgetti\Documentation\Stage\*.txt| Where-Object 
{$_.Name -match "^.+?\.D(\d{6}).*" -gt $date.ToString('MMddyy')| move-item -destination $archive

Will this work how I am expecting? I want to pull all text docs from the stage. where they have a date in them somewhere. check their age against the variable get-date set to a string value. Compare and move.

There are a couple of problems with your Where-Object scriptblock. There's a missing closing } and -match returns a True/False which you're trying to do a greater than comparison with a string. Try changing to this:

... | Where {if ($_.Name -match '^.+?\.D(\d{6})') { 
               $fileDate = [DateTime]::ParseExact($matches[1], "MMddyy", $null)
               $fileDate -gt $date
            }} | Move-Item -Dest $archive

Sorry, that's not going to work, but it's a good idea in general... it just needs a little tinkering to get to work. Where it's going to fail is:

{$_.Name -match "^.+?\.D(\d{6}).*" -gt $date.ToString('MMddyy')| 

That's a malformed Where statement. You have it doing a regex match against a pattern, which if I remember your file name structure correctly it will find. Then you have it matching ??? being greater than a date. Also, you're missing the closing } on it.

couldn't you just do a:

Where{$_.CreationTime -lt (get-date).adddays(-31)}

Then it goes against the creation time not the last modify time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM