Is it possible to create a Database in SQL Server with powershell?

ajack picture ajack · Nov 8, 2011 · Viewed 30.4k times · Source

I am trying to create a empty database in SQL server using powershell and SMO but cannot seem to find a way of doing it. Is this possible?

Connection script for sql server:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

$serverName = "localhost"

$server = new-object ('Microsoft.SqlServer.Management.Smo.Server') $serverName

$server.ConnectionContext.LoginSecure=$false;
$credential = Get-Credential
$loginName = $credential.UserName -replace("\\","")
$server.ConnectionContext.set_Login($loginName);
$server.ConnectionContext.set_SecurePassword($credential.Password)
$server.ConnectionContext.ApplicationName="SQLDeploymentScript"

Answer

Ed Harper picture Ed Harper · Nov 8, 2011

SMO certainly supports a database create method - the linked MSDN page includes a powershell example:

$srv = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, "Test_SMO_Database")
$db.Create()
Write-Host $db.CreateDate