Search code examples
powershellcopy

Powershell - move files from subfolders to parent directory


I have a folder with a lot of folders in it. I want to be able to look in the folder that has been modified today - and only copy the files with a .txt extension. I want to move them up a level. So in the picture below, I only want to search the folder that was modified today (yesterdays date in the picture), no need to check the names of the folders.

If I have a structure like this I want the files in the folders appear directly below in the folder. I also want to check that if there file in the folder that it is not already present in the root folder enter image description here

I have the following code that does move the files, but without the logic for checking the folder with todays modified on and the check if the file is already present.

Get-Childitem -Filter '*.txt' -Path "H:\FOLDERS\" -Recurse | Where lastwritetime -ge $(Get-Date).Date | Copy-Item -Destination "H:\FOLDERS\"

Solution

  • You can try the below code -

    $RootFolder = "H:\Folders"          #Defining the root directory
    $Yesterday = (Get-Date).AddDays(-1) #Last modified date of the folder should be yesterday
    $RecentFolders = Get-Childitem $RootFolder | Where-Object {$_.lastwritetime -gt $Yesterday.date}
    
    foreach($file in $RecentFolders.FullName)
    {
        $Destination = Split-Path $file         #Selecting one folder up
        $TxtFile = Get-Childitem -path $file -filter '*.txt'    #Text files selected
        Copy-Item $TxtFile.FullName -Destination $Destination   #Copy operation
    
    }
    

    If you want to select only those folders which are modified today, you can change the variables as

    $Today = Get-Date
    $RecentFolders = Get-Childitem $RootFolder | Where-Object {$_.lastwritetime -gt $Today.date}