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"
You can create a resource group, server, and single database using Azure PowerShell.
SQL Server versionsSQL PowerShell cmdlets can be used to manage instances of Azure SQL Database, Azure Synapse Analytics, and all supported SQL Server products.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With