user6391187
user6391187

Reputation: 87

Copy and Rename Files Modified in Last Day Using Powershell

I am trying to copy over files from a source folder to a destination folder. I would like to only copy files that have been modified in the last 20 mins. While I am copying I would also like to append the date and time to the end of the file name. The script I currently have is:

$DestinationFolder = "C:\Output\"
$timespan = new-timespan -minutes 20
$Files = Get-ChildItem "C:\Input\*" -File
foreach ($File in $Files) {
    if ($File.LastWriteTime -gt $timespan)
    {
        Copy-Item -Path $_.FullName -Destination $DestinationFolder$($_.BaseName)_$ ($_.LastWriteTime.ToString('yyyyMMdd_hhmmss'))$($_.Extension)
    }
}

I am getting error messages in powershell when I attempt to test my scipt:

Could not compare "07/21/2017 07:31:01" to "00:20:00". Error: "Cannot convert the "00:20:00" value of type "System.TimeSpan" to type "System.DateTime"." At line:2 char:9 + if ($File.LastWriteTime -gt $timespan) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : ComparisonFailure

Upvotes: 1

Views: 1173

Answers (2)

Bacon Bits
Bacon Bits

Reputation: 32145

You're comparing a DateTime with a TimeSpan. That doesn't make sense. A datetime is a point in time. A timespan is a duration. You need to compare two dates.

Try:

$DestinationFolder = "C:\Output\"
$Cutoff = (Get-Date).AddMinutes(-20)
Get-ChildItem "C:\Input\*" -File | Where-Object {
    $_.LastWriteTime -gt $Cutoff
} | ForEach-Object {
    $DestinationFileName = '{0}_{1:yyyyMMdd_HHmmss}{2}' -f $_.BaseName, $_.LastWriteTime, $_.Extension
    $DestinationFullFileName = Join-Path -Path $DestinationFolder -ChildPath $DestinationFileName
    Copy-Item -Path $_.FullName -Destination $DestinationFullFileName
}

I can't tell if there's a bug in your Copy-Item line or not. You may want a dollar sign and a space in there before the date, but I'm guessing that's not right.

Upvotes: 5

Jason Snell
Jason Snell

Reputation: 1465

According to the error you pasted Powershell is having trouble converting a System.TimeSpan to the type System.DateTime. Those are two different objects and you will have to cast one into the other before they will work together.

Upvotes: 3

Related Questions