Copy to Clipboard
# Adjustable settings
$FromPath = "C:\Users\Admin\Desktop\New folder\From"
$ToPath = "C:\Users\Admin\Desktop\New folder\To"
$FolderPrefix = "Path-"
$KeepDays = 7
$DateFormat = "yyyy-MM-dd"
$Counter = 0
$TodayDate = Get-Date -Format $DateFormat
$ToPathPrefix = "$($ToPath)\$($FolderPrefix)"
$ToPathFull = "$($ToPath)\$($FolderPrefix)$($TodayDate)"
#Write-Host "Creating the folder $($ToPath)\$($FolderPrefix)$($Counter)"
if ( ( Test-Path $ToPathFull ) -eq $false ){ New-item -Path $ToPathFull -ItemType "directory" } # Create folder if it doesn't exist
Write-Host "From Path: $($FromPath)"
Write-Host "To Path: $($ToPathFull)"
# Run Robocopy to make a full backup.
# You may want to add '/mt' to copy multiple files at once, depending the types of drives
# You may want to add '/copyall' to copy NTFS permissions if that is important
robocopy /mir /xj /r:0 "$FromPath" "$ToPathFull"
#Remove old folders if needed
$Folders = Get-ChildItem -Directory $ToPath | Sort-Object -Descending -Property Name
foreach ($Folder in $Folders ){
$Date = $Folder.FullName.Substring($ToPathPrefix.length)
if ( $Date.length -eq $DateFormat.Length -and $Folder.FullName.StartsWith($ToPathPrefix) ){
$Counter++
if ( $Counter -gt $KeepDays ){
#Enough matching folders were found, time to delete the rest
Write-Host "Removing folder $($Folder.FullName)"
Remove-Item -Recurse -Force $Folder.FullName
}
}else{
Write-Host "Skipping the folder $($Folder.FullName)"
}
}
# Run Robocopy once more, in case drive filled up on first copy
robocopy /mir /xj /r:0 "$FromPath" "$ToPathFull"
Write-Host "`r`n`r`n`r`nBackup finished!"
An example batch file to run the script: Copy to Clipboard
@echo off
PowerShell.exe -ExecutionPolicy Bypass -File "C:\Users\Admin\Desktop\New folder\BackupDrive.ps1"
echo.
echo.
echo This backup has finished. You may close this window.
pause
|