Is it possible to create a Database in SQL Server with powershell?
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
In my go.bat script, that sets up the environment for the service, I check if the db exists, and if it doesn't, I create one.
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") .
$dbExists = $FALSE
foreach ($db in $server.databases) {
if ($db.name -eq "Db") {
Write-Host "Db already exists."
$dbExists = $TRUE
}
}
if ($dbExists -eq $FALSE) {
$db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -argumentlist $server, "Db"
$db.Create()
$user = "NT AUTHORITY\NETWORK SERVICE"
$usr = New-Object -TypeName Microsoft.SqlServer.Management.Smo.User -argumentlist $db, $user
$usr.Login = $user
$usr.Create()
$role = $db.Roles["db_datareader"]
$role.AddMember($user)
}