Patch/Cmdlets/SQL/Backup-NAVSqlDatabase.ps1
<#
.SYNOPSIS Create a backup file of the provided database from the SQL Server instance. .DESCRIPTION Create a backup file of the provided database from the SQL Server instance. .PARAMETER DatabaseServer Specifies the SQL Server database server. .PARAMETER DatabaseInstance Specifies the SQL Server instance. .PARAMETER DatabaseName Specifies the database name. .PARAMETER DatabaseBackupFilePath Specifies the location of the backup file to be created. #> function Backup-NAVSqlDatabase { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$DatabaseServer = "localhost", [parameter(Mandatory=$false)] [string]$DatabaseInstance = "", [parameter(Mandatory=$true)] [string]$DatabaseName, [parameter(Mandatory=$true)] [string]$DatabaseBackupFilePath ) PROCESS { $CurrentLocation = Get-Location try { if(!(Test-NAVDatabaseOnSqlInstance -DatabaseServer $DatabaseServer -DatabaseInstance $DatabaseInstance -DatabaseName $DatabaseName)) { Write-Error "Database '$DatabaseName' does not exist on SQL Server instance '$DatabaseServer\$DatabaseInstance'" return } $SqlServerInstance = Get-SqlServerInstance -DatabaseServer $DatabaseServer -DatabaseInstance $DatabaseInstance Remove-SqlConnectionsToDatabase -DatabaseServer $DatabaseServer -DatabaseInstance $DatabaseInstance -DatabaseName $DatabaseName $query = "BACKUP DATABASE `"$DatabaseName`" TO DISK = '$DatabaseBackupFilePath'" Invoke-Sqlcmd $query -ServerInstance $SqlServerInstance } finally { Set-Location $CurrentLocation } } } Export-ModuleMember -Function Backup-NAVSqlDatabase |