Search code examples
powershellcopy-item

PowerShell: Copy-Item ignoring LastWriteTime on Objects


Overflow,

I have a task to copy hundreds of files, folders, and subfolders from an on-prem server to location on our shared network drive and am trying to write a Powershell script to accomplish this task.

Powershell is not my strong suite so have been trawling other Stack Overflow posts to see if any can aid in my issue.

For some reason, my script is ignoring the .AddDays component when checking LastWriteTime of files/folders. Code below:

    Get-ChildItem -Path 'E:\Shares' -Recurse |
    Where-Object {$_.LastWriteTime -le (Get-Date).AddDays(-30)} |
    Foreach-Object { ROBOCOPY “E:\Shares\$($_.name)” “\\network.local\Backup\$($_.name)”}

What i actually want it to do is only move files, folders, and subfolders that within the last 90 days. However when testing by using AddDays(-30) it is still copying older items.

How can i stop it doing this? What am i missing here?

Any guidance would be much appreciated, Cheers, L


Solution

  • You want to use -ge (greater or equal to) or -gt (greater than), rather than -le (less or equal to).

    What you're effectively doing is taking the current date, subtracting 30 (in your code, not description) days from that, and then selecting all files that are less than that date, eg BEFORE that date. So you're getting the opposite result from what you're looking for.

    Assuming you do want the last 90 days rather than the 30 used in your code, you'd want to use

    Get-ChildItem -Path 'E:\Shares' -Recurse |
        Where-Object {$_.LastWriteTime -ge (Get-Date).AddDays(-90)} |
        Foreach-Object { ROBOCOPY “E:\Shares\$($_.name)” “\\network.local\Backup\$($_.name)”}
    

    to achieve what you're looking for.