Created
March 28, 2019 12:59
-
-
Save SQLvariant/95fb2c060e47453638b6ef7747e7f68c to your computer and use it in GitHub Desktop.
Find the file-name of the most recent Full Database Backup for a SQL Server database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Find-MostRecentFullBackup([string]$ServerInstance, $database="master"){ | |
#$db = "Adventureworks" | |
$rs = Invoke-Sqlcmd -ServerInstance $ServerInstance -Database msdb -Query " | |
WITH LatestBackupSet (database_name, BackupsAgo, backup_start_date, media_set_id) | |
AS | |
( | |
SELECT database_name | |
, ROW_NUMBER() OVER (PARTITION BY database_name ORDER BY backup_start_date DESC) AS 'BackupsAgo' | |
, backup_start_date | |
, media_set_id | |
FROM msdb.dbo.backupset bs | |
WHERE type != 'L' | |
) | |
SELECT bf.physical_device_name, lbs.* | |
FROM dbo.backupmediafamily bf | |
JOIN LatestBackupSet lbs | |
ON lbs.media_set_id = bf.media_set_id | |
AND lbs.BackupsAgo = 1 | |
AND family_sequence_number = 1 | |
AND lbs.database_name = '$database' | |
" | |
$rs.physical_device_name | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment