1

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

user6391187
  • 87
  • 3
  • 13
  • 1
    What errors are you getting? Error messages in PowerShell are ***usually*** pretty informative, both as to what is wrong and where it's wrong. If you include the error messages in your question, it will be easier to assist you. – Jeff Zeitlin Jul 24 '17 at 17:59

2 Answers2

5

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.

Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
  • @user6391187 I've also corrected the datetime format to use 24 hour time (`HH`). Your existing format only used 12 hour time (`hh`) which could result in confusion. – Bacon Bits Jul 24 '17 at 18:38
3

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.

Jason Snell
  • 1,425
  • 12
  • 22