plasteezy
plasteezy

Reputation: 317

How do I backup my mssql database using powershell

I keep getting this error anytime i run my powershell script to backup my databases. I can't seem to figure out what the problem is. Any help will be most appreciated.

Exception calling "SqlBackup" with "1" argument(s): "Backup failed for Server 'MyServer'. "
At C:\Users\hp1\Desktop\scripts\backup.ps1:28 char:5
+     $smoBackup.SqlBackup($server)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FailedOperationException

My powershell script is shown below:

param(
    $serverName,
    $backupDirectory,
    $daysToStoreBackups
)

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null

$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $serverName
$dbs = $server.Databases
foreach ($database in $dbs | where { $_.IsSystemObject -eq $False })
{
    if($db.Name -ne "tempdb") #We don't want to backup the tempdb database 
     {
    $dbName = $database.Name

    $timestamp = Get-Date -format yyyy-MM-dd-HHmmss
    $targetPath = $backupDirectory + "\" + $dbName + "_" + $timestamp + ".bak"

    $smoBackup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
    $smoBackup.Action = "Database"
    $smoBackup.BackupSetDescription = "Full Backup of " + $dbName
    $smoBackup.BackupSetName = $dbName + " Backup"
    $smoBackup.Database = $dbName
    $smoBackup.MediaDescription = "Disk"
    $smoBackup.Devices.AddDevice($targetPath, "File")
    $smoBackup.SqlBackup($server)
    }
    #"backed up $dbName ($serverName) to $targetPath"
}

Get-ChildItem "$backupDirectory\*.bak" |? { $_.lastwritetime -le (Get-Date).AddDays(-$daysToStoreBackups)} |% {Remove-Item $_ -force }
"removed all previous backups older than $daysToStoreBackups days"

Upvotes: 2

Views: 7702

Answers (2)

sai
sai

Reputation: 11

mkdir D:\kings Invoke-Sqlcmd -Query "backup database Neelamsainaidu to disk='D:\kings\Neelammss.BAK'" -ServerInstance MSWORK-PC -Database Neelamsainaidu

Upvotes: 0

plasteezy
plasteezy

Reputation: 317

I found the problem. It had to do with permissions to the destination folder for the SQL Server Service Account. A common problem when backing up is checking that the SQL Server Service Account has the correct permissions to access the destination. PowerShell is just submitting T-SQL to SQL Server to execute, so the account running the script must have the requisite permissions. Once I gave it read/write everything worked well

Upvotes: 2

Related Questions