Backup Microsoft SQL Server database using PowerShell

During development we need often create backup of Microsoft SQL Server database. Performing this task using SSMS UI dialog is slow and time consuming activity. This task can be automatized by following PowerShell script:

param
(
    [string] $databaseName = $(throw "Database name is required"),
    [string] $backupToDir = ".",
    [bool] $shrinkLogFile = $true
)

Import-Module SQLPS

if ($backupToDir -eq ".")
{
    $backupToDir = (Get-Item .).FullName + "\Backups\"

    if (-not (Test-Path $backupToDir))
    {
        New-Item -Path $backupToDir -ItemType Directory | Out-Null
    }
}

if ($shrinkLogFile)
{
    $shrinkCommand = "DBCC SHRINKFILE (" + $databaseName + "_log, 0)"
    Invoke-Sqlcmd -ServerInstance . -Database $databaseName -Query $shrinkCommand | Out-Null
}

$now = (Get-date).ToString("yyyyMMddHHmmss")
$backupCommand = "BACKUP DATABASE " + $databaseName + " TO DISK='" + $backupToDir + $databaseName + "_" + $now + ".bak' WITH COMPRESSION"

Invoke-Sqlcmd -ServerInstance . -Query $backupCommand


Udemy course: Improve your productivity with PowerShell

The script shrinks database log file and backup is created with compression to decrease the size of backup file.

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.

Analyse log files using PowerShell

PowerShell is great tool for analysing log files. Using few PowerShell cmdlets pipelined together we can find errors:

Get-Content *.log | Select-String error | Sort-Object | Get-Unique | Out-File error.log -Width 1000 -Encoding UTF8


Udemy course: Improve your productivity with PowerShell

Purpose of cmdlets is following:

This simple, but powerfull one line code snippet can help find specific items in log files fast and effectively.

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.