Powershell copying files only from yesterday

AsiekG 41 Reputation points
2021-03-10T16:21:16.41+00:00

Hi,

Tried searching the forum but couldn't find any working solution for my situation.
I'm trying to copy files from one folder to another with the condition that it can only copy files which were created only yesterday.
All other older or newer files should not be copied.

I tried altering this persons code: https://stackoverflow.com/questions/59052724/powershell-script-copying-file-from-yesterday-to-other-folder/66568079?noredirect=1#comment117676904_66568079

To this:

$DestinationFolder = "D:\test\upload"
If(!(test-path $DestinationFolder))
{
      New-Item -ItemType Directory -Force -Path $DestinationFolder
}
$EarliestModifiedTime = (Get-date).AddDays(-1)
$Files = Get-ChildItem "D:\test\*.*" -File
foreach ($File in $Files) 
{
    if ($File.CreationTime -lt $EarliestModifiedTime)
    {
        Copy-Item $File -Destination $DestinationFolder
        Write-Host "Copying $File"
    }
    else 
    {
        Write-Host "Not copying $File"
    }
}

But then it copied all older files together with those from yesterday. Which is obvious because of the "-lt" parameter. When I try to change that to "-eq" it does not work.

It does not want to copy, I get this message:

PS H:\> C:\test\testcopyps.ps1
Not copying D:\test\1.txt
Not copying D:\test\2.txt
Not copying D:\test\3.txt
Not copying D:\test\4.txt
Not copying D:\test\5.txt
Not copying D:\test\6.txt
Not copying D:\test\a.txt

PS H:\> 

But the 1,2,3 text files are actually created yesterday so it should be equal to the $EarliestModifiedTime variable.
What am I doing wrong?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2021-03-10T19:20:12.687+00:00

    See if this works any better.

    $DestinationFolder = "D:\test\upload"
    If (-not (Test-Path $DestinationFolder) ) {
        New-Item -ItemType Directory -Force -Path $DestinationFolder
    }
    $EarliestModifiedTime = (Get-Date).AddDays(-1).Date     # 12AM yesterday
    $LatestModifiedTime = (Get-Date).Date                   # 12AM today
    Get-ChildItem "D:\test\*.*" -File |
        ForEach-Object {
            if ( ($_.CreationTime -ge $EarliestModifiedTime) -and ($_.CreationTime -lt $LatestModifiedTime) ){   # i.e., all day yesterday
                Copy-Item $_ -Destination $DestinationFolder
                Write-Host "Copied $_"
            }
            else {
                Write-Host "Not copying $_"
            }
        }
    
    2 people found this answer helpful.

7 additional answers

Sort by: Most helpful
  1. Vaibhav Chaudhari 38,916 Reputation points Volunteer Moderator
    2021-03-10T16:37:35.56+00:00

    Could you check if below code works?

    $DestinationFolder = "D:\test\upload"
     If(!(test-path $DestinationFolder))
     {
           New-Item -ItemType Directory -Force -Path $DestinationFolder
     }
     $EarliestModifiedTime = (Get-date).AddDays(-1).ToString("MM/dd/yyyy")
    
     $Files = Get-ChildItem "D:\test\*.*" -File
    
     foreach ($File in $Files) 
     {
         if ($File.LastWriteTime.ToString("MM/dd/yyyy") -eq $EarliestModifiedTime)
         {
             Copy-Item $File -Destination $DestinationFolder
             Write-Host "Copying $File"
         }
         else 
         {
             Write-Host "Not copying $File"
         }
     }
    

    Please don't forget to Accept Answer and Up-vote if the response helped -- Vaibhav

    1 person found this answer helpful.
    0 comments No comments

  2. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2021-03-10T16:48:12.163+00:00

    Hi anonymous user ,

    if you wan't to copy only files created yesterday (not older and not newer) you might need 2 "dates" like $EarliestModifiedTime = (Get-date).AddDays(-1) and $NotOlderThanTime = (Get-date).AddDays(-2) .

    The criteria should be like ($File.CreationTime -lt $EarliestModifiedTime) -and ($File.CreationTime -gt $NotOlderThanTime) .

    Be aware Get-Date contains date and time details. If you run the script "today at 5:00 PM" you get "yesterday 5:00 PM" in your variable.
    Which means files created yesterday at 10:00 AM are out of scope.
    If you want "yesterday 0:00" until "yesterday 24:00" maybe this helps: (Get-date -Hour 0 -Minute 0 -Second 0).AddDays(-1) and (Get-date -Hour 0 -Minute 0 -Second 0)


    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    1 person found this answer helpful.

  3. AsiekG 41 Reputation points
    2021-03-11T10:00:37.467+00:00

    Hi anonymous userChaudhari So this seems to be working for the test files. But not for the files I'm trying to use it on. Below you can see the script executing: As expected it skips all files before yesterday and from today. It only tries to copy the files from yesterday: Not copying IN1052280.pdf Not copying IN1052281.pdf Copy-Item : Cannot find path 'H:\IN1052282.pdf' because it does not exist. At C:\test\testcopyps.ps1:14 char:11 + Copy-Item $File -Destination $DestinationFolder + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (H:\IN1052282.pdf:String) [Copy-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand Copying IN1052282.pdf Copy-Item : Cannot find path 'H:\IN1052284.pdf' because it does not exist. At C:\test\testcopyps.ps1:14 char:11 + Copy-Item $File -Destination $DestinationFolder + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (H:\IN1052284.pdf:String) [Copy-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand Copying IN1052284.pdf Copy-Item : Cannot find path 'H:\IN1052289.pdf' because it does not exist. At C:\test\testcopyps.ps1:14 char:11 + Copy-Item $File -Destination $DestinationFolder + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (H:\IN1052289.pdf:String) [Copy-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand Copying IN1052289.pdf Copy-Item : Cannot find path 'H:\IN1052290.pdf' because it does not exist. At C:\test\testcopyps.ps1:14 char:11 + Copy-Item $File -Destination $DestinationFolder + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (H:\IN1052290.pdf:String) [Copy-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand Copying IN1052290.pdf Not copying IN1052291.pdf Not copying IN1052292.pdf Not copying IN1052293.pdf Not copying IN1052294.pdf Here are the files in the folder: ![76697-image.png][1] But it cannot find it somehow? Why does it try to search it in H:\ ? Is it because of the timestamp? Here is the code with the location for the files that I'm trying to use it on: $DestinationFolder = "D:\test\upload" If(!(test-path $DestinationFolder)) { New-Item -ItemType Directory -Force -Path $DestinationFolder } $EarliestModifiedTime = (Get-date).AddDays(-1).ToString("MM/dd/yyyy") $Files = Get-ChildItem "D:\axdocs\AX2012-LIVE\XNL\SalesInvoices\axreports-signed\2021-03" -File foreach ($File in $Files) { if ($File.LastWriteTime.ToString("MM/dd/yyyy") -eq $EarliestModifiedTime) { Copy-Item $File -Destination $DestinationFolder Write-Host "Copying $File" } else { Write-Host "Not copying $File" } } [1]: /api/attachments/76697-image.png?platform=QnA

    0 comments No comments

  4. AsiekG 41 Reputation points
    2021-03-11T11:18:21.797+00:00

    Hi @Andreas Baumgarten :

    I tried your suggestion. You mean like this?

    $DestinationFolder = "D:\test\upload"  
    If(!(test-path $DestinationFolder))  
    {  
            New-Item -ItemType Directory -Force -Path $DestinationFolder  
    }  
    $EarliestModifiedTime = (Get-date -Hour 0 -Minute 0 -Second 0).AddDays(-1)  
    $NotOlderThanTime = (Get-date -Hour 0 -Minute 0 -Second 0).AddDays(-2)  
      
           
    $Files = Get-ChildItem "D:\test\*.*" -File  
          
    foreach ($File in $Files)   
    {  
          if ($File.CreationTime -lt $EarliestModifiedTime) -and ($File.CreationTime -gt $NotOlderThanTime)  
          {  
              Copy-Item $File -Destination $DestinationFolder  
              Write-Host "Copying $File"  
          }  
          else   
          {  
              Write-Host "Not copying $File"  
          }  
    }  
    

    I get this error unfortunately:

    PS H:\> C:\test\testcopyps.ps1  
    At C:\test\testcopyps.ps1:14 char:55  
    +       if ($File.CreationTime -lt $EarliestModifiedTime) -and ($File.CreationTime ...  
    +                                                       ~  
    Missing statement block after if ( condition ).  
        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException  
        + FullyQualifiedErrorId : MissingStatementBlock  
       
      
    PS H:\>   
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.