Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Wednesday, 2 February 2022

Find and copy files updated after certain timestamp

The ask was simple. I had to find the files which are updated post a timestamp lets say this new year i.e. 01/01/2022. And then copy these files to a different folder. Ideally, it can be done manually in few mins but due to bad habit of over-engineer things, we landed up with the script. 

The reason it turned out to be a really useful script because - 
  1. There were hundreds of folder and thousands of file to work with. 
  2. It extracted the files while retaining the original folder structure. Which means that we can paste this folder back anytime we want and it will only updated the extracted files. 
Sample script 
  $cutOff = Get-Date '01/01/2022 00:00' 
    $source ="YOUR\SOURCE\FOLDER\LOCATION\HERE" 
    $destination = "YOUR\DESTINATION\FOLDER\LOCATION\HERE" 
  #Below line fetches all the files | Then check the last updated time | Then it loops through all the files 
  Get-ChildItem $source -File -Recurse | Where {( $_.LastWriteTime -ge $cutOff)} | ForEach { 
      #Extract the full directory path without file name 
     $actualSource = Split-Path $_.FullName 
    #Replace the root source path with root destination path in order to get proper folder structure
     $actualDest = $actualSource.Replace($source, $destination) 
    #copy file from source to destination 
     robocopy $actualSource $actualDest $_.Name 
}