Sunday, December 13, 2020

BACKUP YOUR FILES WITH SIMPLE POWERSHELL FUNCTION

 

BACKUP YOUR FILES WITH SIMPLE POWERSHELL FUNCTION

Following PowerShell will help you to create backup of any desired folder and its content. When running this simple PowerShell function, you will need to provide source and destination variables as shown below.

 

  # Add VARS

 $BackSource = "C:\Users\12024\OneDrive - wiretecpro\Documents\S_Root\"

 $DestSource = "C:\Users\12024\OneDrive - wiretecpro\Documents\Backup\"

 

 

  function Function-Backup{

   

    [CmdletBinding()]

    param(

    [Parameter(Position=0,mandatory=$true)]

    [string] $BackSource,

    [string] $DestSource

    )

 

Try{

 

# Add VARS , start with backup Folder Name

$folderName = 'MyBackup\'

 

# Consantrate Vars

$now = (get-Date -format 'dd-MMM-yyyy-HH-mm-ss-tt')

$BackupFolder  = $folderName+$now

$DestSourceFol =  $DestSource+$BackupFolder

 

# Check DESTINATION Folder, create one if does not exist

if(!(Test-Path  $DestSourceFol)){

 

New-Item $DestSourceFol -ItemType Directory | Out-Null

 

}

 

# Check SOURCE Folder, Stop script if source folder path is not valid

if(!(Test-Path $BackSource)){

Write-Warning 'CANNOT Locate Source'

Write-Warning 'Script will stop'

Start-Sleep -Seconds 3

break;

 

}

 

# Collect all files

$files = (Get-ChildItem $BackSource -recurse)

Write-host 'Backup in progress' -ForegroundColor Green

 

# Start Item by Item Copy

foreach ($file in $files)

{

    if ($file.LastWriteTime -lt ($(Get-Date).AddDays(-1)))

    {  

     Copy-Item $file.FullName -Destination $DestSourceFol -Recurse

 

    }

}

 

# Complete Backup

Write-Host "Completed backup"

 

}Catch{

  $errormessage = $($PSItem.ToString())

  Write-Warning 'Error has occoured'

  Write-host 'Problem FOUND:' $errormessage -ForegroundColor Red -BackgroundColor White

      }

  }

 

 

 

 

  # Add VARS

 $BackSource = "C:\Users\12024\OneDrive - wiretecpro\Documents\S_Root\"

 $DestSource = "C:\Users\12024\OneDrive - wiretecpro\Documents\Backup\"

 

 # Run the function

 Function-Backup -BackSource $BackSource -DestSource $DestSource 

 

 

Casey, Dedeal

Principal Systems Engineer

https://simplepowershell.blogspot.com/  (blog)

https://smtp25.blogspot.com/ (blog)

https://telnet25.wordpress.com/ (blog)

https://twitter.com/Message_Talk (Twitter)

No comments:

Post a Comment

Setting up ISE Profile with Options

  Here is updated ISE profile. You can use it to built your own and make few adjustments.       # STARTING ADDS-ON MENU # ...