Friday, 5 January 2018

How to Schedule SQL Database backup Task with Powershell?

We're done with  SQL DB Backup using Powershell
Now my goal is to make it automated and Scheduled, and we can achieve this with 'ScheduledTask' command of PowerShell.

schedule-database-backup-with-powershell

To create schedule task we basically require four main things:

Define an ScheduledTaskAction
Will create         ScheduledTaskTrigger
Create NewScheduledTask
Registered Register-ScheduledTask

So let's start practically,

First will write script to generate db_backup with powershell script (click here)

Once done with this now we're going to create scheduledTask by following steps:

1. will initialize variables

   $TaskName = "ScheduledDBBackupTask"
   $TaskCommand = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
   $TaskScript = "D:\DB_Backup.ps1"
 
2. here we're defining an action

   $Action = New-ScheduledTaskAction -Execute $TaskCommand -Argument "-NONInteractive -NoLogo -NoProfile -File $TaskScript"

3. here setting up the trigger, (our task will run everyday at 05:35PM)

   $Trigger = New-ScheduledTaskTrigger -Daily -At '05:35PM'
 
4. here creating new scheduledtask

   $Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings (New-ScheduledTaskSettingsSet)
 
5. task has been created, now it's time to register this newly created task:
         
   $Task | Register-ScheduledTask -TaskName $TaskName
 
    For source code of this script click here

once tasted on your local and if you not required in future then remove scheduledtask by

Unregister-ScheduledTask ScheduedDBBackupTask

To verfiy that your custom scheduled task has been removed:

Get-ScheduledTask

Happy Scripting

How to take backup of SQL Database with Powershell?

PowerShell, gives us power to do task very quickly just by writing few line of magical scripts.
Today was looking to create backup of SQL database with the help of Windows Powershell and believe me it's too easy and fast.
database-backup-powershell

So let's start,

$Server = '<Server_Name>' 
$Database = '<Database_Name>'
$FilePath = '<TargetPath/Backup_FileName.bak>' 
Backup-SqlDatabase -ServerInstance $Server -Database $Database -BackupFile $FilePath 


for source code please click here
For example:

$Server = 'SQLServer'
$Database = 'POCDatabase'
$FilePath = 'C:\POCDatabase.bak'
Backup-SqlDatabase -ServerInstance $Server -Database $Database -BackupFile $FilePath

That's it, now check the backup file at target path.

@Note Sometime Backup-SqlDatabase commands not exist, then in this case have to manually add module to the PowerShell related to SQL by

Import-Module SQLPS

after importing module again try the above scripts.