Friday, August 19, 2016

PowerShell - List databases and check database backup times

# Import SQL Server module
Import-Module SQLPS -DisableNameChecking

# Connect to the server
$instanceName = "localhost"
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

$folder = "c:\temp"
$currdate = Get-Date -Format "yyyy-MM-dd_HHmm"
$filename = "$($instanceName)_db_$($currdate).csv"
$fullpath = Join-Path $folder $filename

# Create a dynamic array
$result = @()

# Go through each database and build the result set
$server.Databases | ForEach-Object {
    
    $db = $_
    
    $item = [PSCustomObject] @{
        DatabaseName = $db.Name
        RecoveryModel = $db.RecoveryModel
        LastBackupDate = $db.LastBackupDate
        LastLogBackupDate = $db.LastLogBackupDate
    }

    $result += $item

}

# Dashes
Write-Host $('-' * 70)


# Display result
$result | Format-Table -AutoSize


# Export result to CSV
$result | Export-Csv -Path $fullpath -NoTypeInformation

# Fires off Excel and displays the csv file
explorer $fullpath


############################################################################

# This approach is more concise:

$instanceName = "beuscbetlsql"
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

$server.Databases | Select-Object Name, RecoveryModel, LastBackupDate, LastLogBackupDate | Format-Table -AutoSize