Skip to content

Instantly share code, notes, and snippets.

@ghotz
Last active August 29, 2015 14:01
Show Gist options
  • Save ghotz/1178dd91c79cf487c58f to your computer and use it in GitHub Desktop.
Save ghotz/1178dd91c79cf487c58f to your computer and use it in GitHub Desktop.
Get transaction log backup LSN (log sequence number) for a database
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO');
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended');
$SQLInstance = New-Object "Microsoft.SqlServer.Management.Smo.Server" "localhost";
$DatabaseName = "TestDB";
$QueryStmt =
@"
SELECT last_log_backup_lsn
FROM sys.database_recovery_status
WHERE database_id = DB_ID('$DatabaseName');
"@;
$QueryResult = $SQLInstance.ConnectionContext.ExecuteWithResults($QueryStmt);
if ($QueryResult.Tables[0].Rows[0] -eq $null)
{ Write-Output "Empty result set, database doesn't exist."; }
else
{
$LastLogBackupLSN = $QueryResult.Tables[0].Rows[0]["last_log_backup_lsn"];
if ($LastLogBackupLSN -is [System.DBNull])
{ Write-Output "Last Log Backup LSN is NULL, full backup not run yet or database in in simple recovery model."; }
else
{ Write-Output "Last Log Backup LSN for database [$($DatabaseName)] is $($LastLogBackupLSN)."; };
};
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO');
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended');
$SQLInstance = New-Object "Microsoft.SqlServer.Management.Smo.Server" "localhost;
$QueryStmt =
@"
SELECT last_log_backup_lsn
FROM sys.database_recovery_status
WHERE database_id = DB_ID('$DatabaseName');
"@;
$QueryResult = $SQLInstance.Databases["master"].ExecuteWithResults($QueryStmt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment