MS SQL 2016 and Powershell RRS feed

  • Question

  • Hi,

    i'm testing the MS SQL 2016 and i have a lot of questions. My first question is:
    How to create a database from PowerShell?
    When i run a command in the SSMS:


    It works. But if i try to repeat the same command from powershell - it doesn't work:

    Invoke-Sqlcmd -Query "CREATE DATABASE "TEST";" -ServerInstance "$SQLServer" -Username $uid -Password $pwd
    Invoke-Sqlcmd : A positional parameter cannot be found that accepts argument 'TEST;'

    another way:

    $SqlQuery = "CREATE DATABASE "TEST";"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; User ID = $uid; Password = $pwd;"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $SqlQuery
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    + $SqlQuery = "CREATE DATABASE "TEST";"
    +                               ~~~~~~~~
    Unexpected token 'TEST";"' in expression or statement.
        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : UnexpectedToken

    I guess that something wrong with " "

    Monday, December 19, 2016 2:34 PM


  • first answer is:

    Invoke-Sqlcmd -Query "CREATE DATABASE [TEST];" -ServerInstance "$SQLServer" -Username $uid -Password $pwd
    • Marked as answer by Anahaym Monday, December 19, 2016 3:17 PM
    Monday, December 19, 2016 3:16 PM