none
PowerShell to move the file which last modify day older than 1 day RRS feed

  • Question

  • Hi,

    I would like to create a PowerSehll file which is used to move the file which last modity day older than 1 day to onther folder. Below is my PowerShell 

    $path = "D:\IIS Log\W3SVC1"
    $Destination = "D:\IIS Log\old"
    Foreach($file in (Get-ChildItem $path))
    {
    If($file.lastModified -gt (Get-Date).adddays(-1).date)
    {
    Move-Item -Path $file.fullname -Destination $Destination
    }
    }

    However, the script seems only to moved the file newer than 1 day to other folder.  Which parameter need to be modified in order to fulfill my requirement?

    Monday, March 27, 2017 10:05 AM

Answers

  • Hi Oscar,

    older dates are smaller than newer dates, so you need to reverse your filter condition:

    # Will move newer files
    if($file.LastWriteTime -gt (Get-Date).adddays(-1).date)
    
    # Will move older files
    if($file.LastWriteTime -lt (Get-Date).adddays(-1).date)

    Cheers,
    Fred


    There's no place like 127.0.0.1


    • Edited by FWN Monday, March 27, 2017 10:30 AM Wrong property name
    • Marked as answer by OscarTC Tuesday, March 28, 2017 5:25 AM
    Monday, March 27, 2017 10:23 AM
  • Hi Oscar,

    just noticed, you also had the wrong property name: Not "lastModified" but rather "LastWriteTime"

    I updated it in my snippet, give it a try.

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by OscarTC Tuesday, March 28, 2017 5:25 AM
    Monday, March 27, 2017 10:30 AM

All replies

  • Hi Oscar,

    older dates are smaller than newer dates, so you need to reverse your filter condition:

    # Will move newer files
    if($file.LastWriteTime -gt (Get-Date).adddays(-1).date)
    
    # Will move older files
    if($file.LastWriteTime -lt (Get-Date).adddays(-1).date)

    Cheers,
    Fred


    There's no place like 127.0.0.1


    • Edited by FWN Monday, March 27, 2017 10:30 AM Wrong property name
    • Marked as answer by OscarTC Tuesday, March 28, 2017 5:25 AM
    Monday, March 27, 2017 10:23 AM
  • Hi Fred,

    Tried but all file will be copied.  There is a file where last modify date is today, but this file will still be moved according to above PowerShell script.

    Monday, March 27, 2017 10:28 AM
  • Hi Oscar,

    just noticed, you also had the wrong property name: Not "lastModified" but rather "LastWriteTime"

    I updated it in my snippet, give it a try.

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by OscarTC Tuesday, March 28, 2017 5:25 AM
    Monday, March 27, 2017 10:30 AM