Purpose: Create an efficient backup process for large directories. Notes: First, the script enumerates all of the files in a specific directory, and stored that data in a variable (SourceFiles). It then check for a matching file in the backup directory. If it does not find a matching file, it simply copies the file and the directory structure. If it does find a matching file, it looks to the LastWriteTime property, and only replaces the backup file is the other file is newer. I do plan to make this a renditional backup at some point when I am more awake. #Set Directory Paths $SourceDirectory = "C:\Scripts" $BackupLocation = "C:\Backup" #Get all files contained in Source Folder for processing $SourceFiles = Get-ChildItem -Path $SourceDirectory -File -Recurse #Create an array to store the output $MoveStats = New-Object System.Collections.ArrayList #Action $MoveStats = ForEach($File in $SourceFiles){ $OldPath = ($File.FullName) $NewPath = $OldPath.Replace($SourceDirectory,$BackupLocation) #Create new object to store output $FileObject = New-Object -TypeName PSCustomObject -Property @{ File = $File.Name OriginalPath = $File.FullName BackupPath = $null Action = $null } #Check for existing file in Backup Location if(Test-Path $NewPath){ #File exists. Check to see if needs updating if(($File.LastWriteTime) -gt ((Get-Item $NewPath).LastWriteTime)){ #Overwrite the file (Will change to renditional in the future.) $FileObject.BackupPath = $NewFile Copy-Item -Path $OldPath -Destination $NewPath -Force $FileObject.Action = "File Updated." } else{ #No action taken $FileObject.BackupPath = $NewPath $FileObject.Action = "No action taken." } } else{ #File does not exist. Copy file. New-Item -ItemType File -Path $NewPath -Force | Out-Null Copy-Item -Path $OldPath -Destination $NewPath $FileObject.BackupPath = $NewPath $FileObject.Action = "New File Copied." } #Returning Object $FileObject } #Display Output $MoveStats | Select File, Action
A Semi-Intelligent File Backup
Saturday, July 12, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Please keep all comments clean!