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

前端 未结 7 2199
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 04:39

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

7条回答
  •  情书的邮戳
    2020-12-09 05:01

    Yes, I am using this in *.ps1 script

    $ConnectionString = "Data Source=.\SQLEXPRESS;initial catalog=master;Integrated Security=True;"
    $NewDatabaseName = "MyDatabase"
    
    $con = New-Object Data.SqlClient.SqlConnection;
    $con.ConnectionString = $ConnectionString;
    $con.Open();
    
    # create the database.
    $sql = "CREATE DATABASE [$NewDatabaseName] COLLATE SQL_Latin1_General_CP1_CI_AS;"
    $cmd = New-Object Data.SqlClient.SqlCommand $sql, $con;
    $cmd.ExecuteNonQuery();     
    Write-Host "Database $NewDatabaseName is created!";
    
    # close & clear all objects.
    $cmd.Dispose();
    $con.Close();
    $con.Dispose();
    

    Check example here http://www.devcode4.com/article/powershell-create-mssql-database

提交回复
热议问题