Wednesday, 29 June 2011

Backup a file using powershell script

Some critical files that I modify each day had to be backed up to a secure location, in case the file gets corrupted I can go to the archive and get the most recent backup.

I created a powershell script to do this. The script is pasted below.
#file name backup.ps1
$PathToGoalsSheet="C:\preformancereports\Akshay"
$FileToBeBackedUp="Goals.xlsx"
$BackupPath="D:\myComany\Dept\Backup"
$TodaysDateFormatted = Get-Date -format dd.MM.yyyy.HH.mm.ss
$BackupFolderName=[string]::Format("{0}.backup",$TodaysDateFormatted)
#Write($BackupFolderName)
if(Test-Path $PathToGoalsSheet)
{
if(Test-Path $PathToGoalsSheet\$FileToBeBackedUp)
{
Write("Creating folder ["+$BackupFolderName+"]...")
New-Item $PathToGoalsSheet\$BackupFolderName -type directory
Write("Copying File ["+ $FileToBeBackedUp +"] into ["+$BackupFolderName+"]...")
Copy-Item "$PathToGoalsSheet\$FileToBeBackedUp" "$BackupPath\$BackupFolderName"
}
else
{
Write("Could not find file ["+ "$PathToGoalsSheet\$FileToBeBackedUp" +"]!")
}
}
else
{
Write("The path ["+$PathToGoalsSheet+"] does not exist!")
}

The command to run this script file, I typed in a batch file (.bat), so I can run the powershell file (or schedule a task to run the batch file on a daily basis). The code in the batch file is as given below.

rem file name backup.bat
@echo off
set scriptHomePath=C:\PowerShell Scripts\
set backupFileScript=%scriptHomePath%backup.ps1
powershell -NoLogo -File "%backupFileScript%"

No comments:

Post a Comment