This article highlights how to use Windows PowerShell to retrieve database properties using SMO. Notice how easy it is to check the database properties using pretty common syntax
One of the challenges I have when I was starting out as a SQL Server DBA was to check for the last backup date for a database. One way to do this is to find out which tables in the MSDB database contain the records of the backup history. What’s really challenging here is the fact that you would have to look at the tables and their corresponding relationships which, apparently, MSDB doesn’t have. You simply have to rely on what SQL Server Books Online has to say. Plus, the MSDB database will only contain records for databases with backups. What about those without?
For SQL Server 2005, the script below displays the last backup date of all the databases on your SQL Server instance. This script is from the MSDN Code Gallery
T1.Name AS DatabaseName,
COALESCE(CONVERT(VARCHAR(12), MAX(T2.backup_finish_date), 101),'Not Yet Taken') AS LastBackUpTaken
FROM sys.sysdatabases T1 LEFT OUTER JOIN msdb.dbo.backupset T2
ON T2.database_name = T1.name
GROUP BY T1.Name
ORDER BY T1.Name
You can simply replace the sys.sysdatabases table with master.dbo.sysdatabases for SQL Server 2000
Below is the equivalent script using Windows PowerShell.
$instance="Your_SQL_Server_Instance_Name" [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')| out-null # Create an SMO connection to the instance $s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $instance $dbs = $s.Databases $dbs | select Name,LastBackupDate, LastLogBackupDate | format-table -autosize
The only thing to note here are the last two lines – the one that creates an instance of the database object and the one that displays and formats a few of the database object properties. The first few lines will be the same for just about any PowerShell script that will access SQL Server using SMO