Last month I presented a session on using PowerShell with SQL Server. One of the complaints I've heard as I've discussed the benefits of using SMO to build management solutions was that DBA's aren't programmers, and don't want to write programs. (Personally, I think script programming is no different from a skills perspective than VB or C# programming, but that's just my opinion.)
PowerShell 1.0 is now available and it uses the .Net 2.0 Framework, so all the capabilities of SMO are available in PowerShell. You have to load the SMO assembly at the start of the script (or put this in your profile script, if you're so inclined), but that's fairly easy to do.
Dan Sullivan has created kind of an add-on to PowerShell he calls PowerSMO which gives you a lot of flexibility in using SMO within PowerShell. I wanted to present SMO directly, and let the reader decide how to best make use of the tools.
In my presentation I showed a few script examples using SMO in PowerShell, the first of which is presented here. It's essentially the same script I've done in VB.Net, but converted to PowerShell, to create a new database with the properties I specify, rather than taking the SQL Server defaults.
#CreateDatabase.ps1
#Creates a new database using our specifications
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
#Instantiate objects for the Server, the Database and the FileGroup
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') 'MyServer'
$db = new-object ('Microsoft.SqlServer.Management.Smo.Database') ($s, "NewDB")
$fg = new-object ('Microsoft.SqlServer.Management.Smo.FileGroup') ($db, "PRIMARY")
#Add the filegroup to the database
$db.FileGroups.Add($fg)
#Instantiate the data file object and add it to the PRIMARY filegroup
$dbdfile = new-object ('Microsoft.SqlServer.Management.Smo.DataFile') ($fg, "NewDB_Data")
$fg.Files.Add($dbdfile)
#Set the properties of the data file
$dbdfile.FileName = "E:\MSSQL\Data\NewDB_Data.mdf"
$dbdfile.Size = [double](25.0 * 1024.0)
$dbdfile.GrowthType = "Percent"
$dbdfile.Growth = 25.0
$dbdfile.MaxSize = [double](100.0 * 1024.0)
#Instantiate the log file object and set its properties
$dblfile = new-object ('Microsoft.SqlServer.Management.Smo.LogFile') ($db, "NewDB_Log")
$dblfile.FileName = "L:\MSSQL\Data\NewDB_Log.ldf"
$dblfile.Size = [double](10.0 * 1024.0)
$dblfile.GrowthType = "Percent"
$dblfile.Growth = 25.0
#Create the database
$db.Create()
In another post I'll demonstrate using PowerShell for regular data access.
Allen