Create SQL Database using PowerShell

email me

Using this PowerShell code, you can either run it directly in the console, or make a CreateDB.ps1 file, to add a new SQL DB. Note, you could use with some of the previous PS code to create a single solution to automate the creation of the database, add the schema, and add tables.


[String]$dbname = "MyNewDatabase";

# Open ADO.NET Connection with Windows authentification to local SQLSERVER.
$con = New-Object Data.SqlClient.SqlConnection;
$con.ConnectionString = "Data Source=.;Initial Catalog=master;Integrated Security=True;";
$con.Open();

# Select-Statement for AD group logins
$sql = "SELECT name
        FROM sys.databases
        WHERE name = '$dbname';";

# New command and reader.
$cmd = New-Object Data.SqlClient.SqlCommand $sql, $con;
$rd = $cmd.ExecuteReader();
if ($rd.Read())
{	
	Write-Host "Database $dbname already exists";
	Return;
}

$rd.Close();
$rd.Dispose();

# Create the database.
$sql = "CREATE DATABASE [$dbname];"
$cmd = New-Object Data.SqlClient.SqlCommand $sql, $con;
$cmd.ExecuteNonQuery();		
Write-Host "Database $dbname is created!";


# Close & Clear all objects.
$cmd.Dispose();
$con.Close();
$con.Dispose();