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

前端 未结 7 2165
隐瞒了意图╮
隐瞒了意图╮ 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:00

    found out how to do this here http://msdn.microsoft.com/en-us/library/ms162577.aspx

    My code now:

    [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"
    
    #Create a new database
    $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -argumentlist $server, "Test_SMO_Database"
    $db.Create()
    
    #Reference the database and display the date when it was created. 
    $db = $server.Databases["Test_SMO_Database"]
    $db.CreateDate
    

提交回复
热议问题