Search code examples
powershelllocaldb

Is there an one-liner to create LocalDB database (not instance) in PowerShell?


I want to create a LocalDB database in a way that MDF and LDF files stay on script execution folder.

  • I know that we can easily do command substitutions with $ operator in PowerShell, so, if I state something like $pwd it will make a substitution with the output of pwd command.

  • From here, I know that Invoke-SqlCmd is not a straightforward way of doing things with LocalDB instances.

  • I want to execute the following command through PowerShell. How could I accomplish that?

    sqlcmd -S "(localdb)\MSSQLLocalDB" -Q "
    CREATE DATABASE [Test] ON PRIMARY ( 
            NAME = N'Test', 
            FILENAME = N'<$pwd output here>\Test.mdf'
    ) 
    LOG ON ( 
            NAME = N'Test_log', 
            FILENAME = N'<$pwd output here>\Test_log.ldf'
    )"
    

Solution

  • This might be a lot more than you are asking, but it will solve your issue.

    This will ask you if you want to restore from a template if no then it will create an empty database.

    $backupFilePath=''
    $TempDB=''
    $TempDBlog=''
    $DBName=''
    $Logfilepath=''
    $Datafilepath=''
    
    $confirmation = Read-Host "Do you want to use a DB template? [y/n]"
    
    If($confirmation.ToUpper().StartsWith("Y") )
    {
    $dbCommand = "use [master];RESTORE DATABASE [$DBName] " + "FROM DISK = N'$backupFilePath'" + "WITH FILE = 1, NOUNLOAD, STATS = 10, " + "move '$TempDB' to '$Datafilepath" + "\" + "$DBName" + ".mdf', " + "move '$TempDBlog' to '$Logfilepath" + "\" + "$DBName" + ".ldf';" + "alter database [$DBName] modify file (name=N'$TempDB ', newname=N'$DBName" + "_data1');" + "alter database [$DBName] modify file (name=N'$TempDBlog', newname=N'$DBName" + "_log1');" + "alter database [$DBName] set read_committed_snapshot on with rollback immediate;" + "alter database [$DBName] set COMPATIBILITY_LEVEL = 100;"
    }
    
    else {
    $dbCommand = "use [master];CREATE DATABASE [$DBName] ON " + "( NAME='$DBName" + "_data1', FILENAME='$Datafilepath" + "\" + "$DBName" + "_data1.mdf', SIZE=1GB, MAXSIZE=UNLIMITED, FILEGROWTH=200MB)" + "LOG ON ( NAME='$DBName" + "_log1', FILENAME='$Logfilepath" + "\" + "$DBName" + "_log1.ldf', SIZE=1GB, MAXSIZE=UNLIMITED, FILEGROWTH=200MB); " + "alter database [$DBName] set read_committed_snapshot on with rollback immediate;" + "alter database [$DBName] set COMPATIBILITY_LEVEL = 100; " + "set AUTO_CLOSE OFF;"
    }
    

    Someone will have to edit this into nice looking code break, because it is not allowing me to do it.