Can PowerShell scripting move files less than 5 minutes old?

9,273

Try the following:

Get-ChildItem |
Where-Object {
  [datetime]::ParseExact($_.BaseName, "yyyyMMddHHmmss", $null) -gt (Get-Date).AddMinutes(-5)
} |
Move-Item -Destination C:\Path\to\target_dir

I split the code up to multiple lines for readability, but you can of course turn it into a one-liner, and even shorten it a bit using PowerShell aliases.


Explanation

  • Get-ChildItem returns a list of all files in the current directory. Note: it also returns subdirectories, but this code assumes you only have files in there. The results are piped (|) to the next command.

  • Where-Object loops through the results from the previous command and returns only those that match the specified criteria. $_ represents the current file of each iteration, and the .BaseName property returns the filename sans extension.

  • The [datetime]::ParseExact() function takes a string and a date format and converts it into a datetime object.

  • Get-Date returns the current date and time. The AddMinutes() function deducts 5 minutes from the current time.

  • The files returned by Where-Object, then, are those where the date and time represented in the filename is no more than 5 minutes older than the current time.

  • Finally, Move-Item moves the matching files to the specified directory.

Share:
9,273

Related videos on Youtube

Grimm
Author by

Grimm

Updated on September 18, 2022

Comments

  • Grimm
    Grimm over 1 year

    We have a network folder used as a holding area for XML files that were not properly processed. I’ve been asked to design a script that runs every five minutes and checks the folder for any files less than five minutes old. If it finds files less than five minutes old, it moves them into another directory to be processed.

    The trick is, we only want it to move the files one time. If they fail a second time, they will be thrown back into that folder and need to remain there to be dealt with later.

    The file names each contain a unique time and date stamp as part of the file name. It’s a little convoluted, but the format is:

    YYYYMMDDHHmmSSSSS
    

    I was thinking there might be a way for PowerShell to look at the “mm” stamp of the filename and compare it to the current time. If it’s less than five minutes old, it moves it. If it’s greater than five minutes old, it leaves it alone.

    Is this possible?

    • Ярослав Рахматуллин
      Ярослав Рахматуллин over 11 years
      Obtain the filename as a string, look at index 10-11 and compare them. A less error prone approach would be to convert the timestamps to the absolute time of the unix epoch (seconds since 1. jan 1970) and do comparisons by subtracting 300. I wish I had a windows box at hand to give you a more concrete example, but this is certainly possible.