question

leeroberts-8039 avatar image
0 Votes"
leeroberts-8039 asked leeroberts-8039 commented

Move only folders that have been modified

I have the below script which i used to copy a set of user folders. I now have to copy them again, But this time only copy the folders / files that have been updated since the last copy. Is this possible?

 $sourcepath = 'c:\temp'
  $targetpath = 'g:\users'
  $mapFile = 'C:\temp\UserNames.csv'
  Import-Csv $mapFile -Header 'OriginalName', 'NewName' | ForEach-Object {
     $src = Join-Path $sourcePath $_.OriginalName
     $dest = Join-Path $targetPath $_.NewName
     if(-not (Test-Path $dest)){ New-Item -Path $dest -ItemType Directory }
     Get-ChildItem -Path $src | Copy-Item -Destination $dest -Recurse }
windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered leeroberts-8039 commented

Hi,

You can compare the LastWriteTime property of the files.

 function UpdateFile{
     param(
         [Parameter(Mandatory = $true)]
         [string]$source
     )
     Get-ChildItem -Path $source | ForEach-Object{
         if($_.PSIsContainer){
             UpdateFile $_.FullName
         }
         else{
             $itempath = $_.FullName.replace($src,$dest)
             if(Test-Path -Path $itempath){
                 $item = Get-Item -Path $itempath
                 if($_.LastWriteTime -ne $item.LastWriteTime ){
                     Copy-Item -Path $_.FullName -Destination $itempath
                 }
             }
             else{
                 $itempath -match '^.*\\' | Out-Null
                 $dirpath = $Matches.Values
                 if(-not(Test-Path -Path $dirpath)){
                     New-Item -Path $dirpath -ItemType Directory
                 }
                 Copy-Item -Path $_.FullName -Destination $itempath
             }
         }
     }
 }
    
 $sourcepath = 'D:\temp'
 $targetpath = 'D:\temp1'
 $mapFile = 'D:\temp1\UserNames.csv'
 Import-Csv $mapFile -Header 'OriginalName', 'NewName' | ForEach-Object {
     $src = Join-Path $sourcePath $_.OriginalName
     $dest = Join-Path $targetPath $_.NewName
     UpdateFile $src
 }

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Once again thank you so much.

Your assistance is always very much appreciated

0 Votes 0 ·