Home
Manage Your Code
Snippet: Create SQL Server Database from PowerShell (PowerShell)
Title: Create SQL Server Database from PowerShell Language: PowerShell
Description: This script creates a SQL Server database from PowerShell. If the database already exists, it deletes it, then re-creates it. Views: 161
Author: Dave Donaldson Date Added: 12/5/2008
Copy Code  
# Get the parameters passed to the script
Param($dbInstance, $dbName)

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$dbServer = new-object Microsoft.SqlServer.Management.Smo.Server ($dbInstance)
$db = new-object Microsoft.SqlServer.Management.Smo.Database

# Loop thru the db list to find the one we need. If found set the local vars
# to avoid errors when trying to delete the db from within the loop.
$found = "false"
foreach ($_ in $dbServer.Databases)
{
    if ($_.Name -eq $dbName)
    {
        $db = $_
        $found = "true"
    }
}

# Now that we're out of the loop we can kill the db
if ($found -eq "true")
{
    "Deleting database $dbName..."
    $dbServer.KillAllProcesses($db.Name)
    $dbServer.KillDatabase($db.Name)
}

"Creating database $dbName..."
$db = new-object Microsoft.SqlServer.Management.Smo.Database ($dbServer, $dbName)
$db.Create()
Notes
Example: If the script is found at C:\temp.ps1 and you want to create a database named MyDatabase on the local default instance (you have to escape the double-quotes that surround (local) for it to picked up by PowerShell): powershell C:\temp.ps1 -dbInstance \"(local)\" -dbName MyDatabase