Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 923
ajack Avatar asked Nov 08 '11 10:11

ajack


People also ask

Can you create a database in PowerShell?

You can create a resource group, server, and single database using Azure PowerShell.

Can we use PowerShell in SQL Server?

SQL Server versionsSQL PowerShell cmdlets can be used to manage instances of Azure SQL Database, Azure Synapse Analytics, and all supported SQL Server products.

How do I create a new database in SQL Server?

Use SQL Server Management StudioRight-click Databases, and then select New Database. In New Database, enter a database name. To create the database by accepting all default values, select OK; otherwise, continue with the following optional steps. To change the owner name, select (...) to select another owner.


2 Answers

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
like image 115
Ed Harper Avatar answered Oct 04 '22 12:10

Ed Harper


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)
}
like image 27
Andrew Chaa Avatar answered Oct 04 '22 13:10

Andrew Chaa