Runs a script containing statements from the languages (Transact-SQL and XQuery) and commands supported by the SQLServer sqlcmd utility.
Invoke-SqlCmd [[-Query] <string>] [-AbortOnError <Boolean>] [-ConnectionTimeout <int>] [-Database <string>][-DedicatedAdministratorConnection <Boolean>] [-DisableCommands <Boolean>] [-DisableVariables <Boolean>][-EncryptConnection <Boolean>] [-ErrorLevel <int>] [-HostName <string>] [-IgnoreProviderContext <Boolean>][-InputFile <string>] [-MaxBinaryLength <int>] [-MaxCharLength <int>] [-NewPassword <string>] [-OutputSqlErrors<Boolean>] [-Password <string>] [-QueryTimeout <int>] [-ServerInstance <psobject>] [-SeverityLevel <int>][-SuppressProviderContextWarning <Boolean>] [-Username <string>] [-Variable <string[]>] [<CommonParameters>]

Runs a script containing the languages and commands supported by the SQL Server sqlcmd utility. The languages supported are Transact-SQL and the XQuery syntax supported by the Database Engine. Invoke-Sqlcmd also accepts many of the commands supported by sqlcmd, such as GO and QUIT. Invoke-Sqlcmd accepts the sqlcmd scripting variables, such as SQLCMDUSER. Invoke-Sqlcmd does not set sqlcmd scripting variables by default.Invoke-Sqlcmd does not support the sqlcmd commands primarily related to interactive script editing. The commands not supported include :!!, :connect, :error, :out, :ed, :list, :listvar, :reset, :perftrace, and :serverlist.The first result set the script returns is displayed as a formatted table. Result sets after the first are not displayed if their column list is different from the column list of the first result set. If result sets after the first set have the same column list, their rows are appended to the formatted table that contains the rows that were returned by the first result set.Invoke-Sqlcmd does not return SQL Server message output, such as the output of PRINT statements, unless you use the PowerShell -Verbose parameter.

-AbortOnError <Boolean>

Specifies that Invoke-Sqlcmd stop running and return an error level to the PowerShell ERRORLEVEL variable if Invoke-Sqlcmd encounters an error. The error level returned is 1 if the error has a severity higher than 10, and the error level is 0 if the error has a severity of 10 or less. If -ErrorLevel is also specified, Invoke-Sqlcmd returns 1 only if the error message severity is also equal to or higher than the value specified for -ErrorLevel.

-ConnectionTimeout <int>

Specifies the number of seconds when Invoke-Sqlcmd times out if it cannot successfully connect to an instance of the Database Engine. The timeout value must be an integer between 0 and 65534. If 0 is specified, connection attempts do not time out.

-Database <string>

A character string specifying the name of a database. Invoke-Sqlcmd connects to this database in the instance that is specified in -ServerInstance.If -Database is not specified, the database that is used depends on whether the current path specifies both the SQLSERVER:SQL folder and a database name. If the path specifies both the SQL folder and a database name, Invoke-Sqlcmd connects to the database that is specified in the path. If the path is not based on the SQL folder, or the path does not contain a database name, Invoke-Sqlcmd connects to the default database for the current login ID. If you specify the -IgnoreProviderContext switch, Invoke-Sqlcmd does not consider any database specified in the current path, and connects to the database defined as the default for the current login ID.

-DedicatedAdministratorConnection <Boolean>

Uses a Dedicated Administrator Connection (DAC) to connect to an instance of the Database Engine. DAC is used by system administrators for actions such as troubleshooting instances that will not accept new standard connections. The instance must be configured to support DAC. If DAC is not enabled, Invoke-Sqlcmd reports an error and stops running.

-DisableCommands <Boolean>

Turns off some sqlcmd features that might compromise security when run in batch files. It prevents PowerShell variables from being passed in to the Invoke-Sqlcmd script. The startup script specified in the SQLCMDINI scripting variable is not run.

-DisableVariables <Boolean>

Specifies that Invoke-Sqlcmd ignore sqlcmd scripting variables. This is useful when a script contains many INSERT statements that may contain strings that have the same format as variables, such as $(variable_name).

-EncryptConnection <Boolean>

Specifies whether Invoke-Sqlcmd uses Secure Sockets Layer (SSL) encryption for the connection to the instance of the Database Engine specified in -ServerInstance. If TRUE is specified SSL encryption is used. If FALSE is specified encryption is not used.

-ErrorLevel <int>

Specifies that Invoke-Sqlcmd display only error messages whose severity level is equal to or higher than the value specified. All error messages are displayed if -ErrorLevel is not specified or set to 0. Database Engine error severities range from 1 to 24.

-HostName <string>

Specifies a workstation name. The workstation name is reported by the sp_who system stored procedure and in the hostname column of the sys.processes catalog view. If HostName is not specified, the default is the name of the computer on which Invoke-Sqlcmd is running. HostName can be used to identify different Invoke-Sqlcmd sessions.

-IgnoreProviderContext <Boolean>

Invoke-Sqlcmd ignores the database context that was established by the current SQLSERVER:SQL path. If the -Database parameter is not specified, Invoke-Sqlcmd uses the default database for the current login ID or Windows account.

-InputFile <string>

Specifies a file to be used as the query input to Invoke-Sqlcmd. The file can contain Transact-SQL statements, XQuery statements, and sqlcmd commands and scripting variables. Specify the full path to the file. Spaces are not allowed in the file path or file name.Only run scripts from trusted sources. Ensure all input scripts are secured with the appropriate NTFS permissions.

-MaxBinaryLength <int>

Specifies the maximum number of bytes returned for columns with binary string data types, such as binary and varbinary. The default is 1,024 bytes.

-MaxCharLength <int>

Specifies the maximum number of characters returned for columns with character or Unicode data types, such as char, nchar, varchar, and nvarchar. The default is 4,000 characters.

-NewPassword <string>

Specifies a new password for a SQL Server Authentication login ID. Invoke-Sqlcmd changes the password and then exits. -Username and -Password must also be specified, with -Password specifying the current password for the login.

-OutputSqlErrors <Boolean>

Specifies whether error messages are displayed in the Invoke-Sqlcmd output.

-Password <string>

Specifies the password for the SQL Server Authentication login ID that was specified in -Username. Passwords are case-sensitive. When possible, use Windows Authentication. Do not use a blank password, when possible use a strong password.

-Query <string>

Specifies one or more queries to be run. The queries can be Transact-SQL or XQuery statements, or sqlcmd commands. Multiple queries separated by a semicolon can be specified. Do not specify the sqlcmd GO separator. Escape any double quotation marks included in the string. Consider using bracketed identifiers such as [MyTable] instead of quoted identifiers such as “MyTable”.

-QueryTimeout <int>

Specifies the number of seconds before the queries time out. If a timeout value is not specified, the queries do not time out. The timeout must be an integer between 1 and 65535.

-ServerInstance <psobject>

A character string or SMO server object specifying the name of an instance of the Database Engine. For default instances, only specify the computer name: “MyComputer”. For named instances, use the format “ComputerNameInstanceName”.

-SeverityLevel <int>

Specifies the lower limit for the error message severity level Invoke-Sqlcmd returns to the ERRORLEVEL PowerShell variable. Invoke-Sqlcmd returns the highest severity level from the error messages generated by the queries it runs, provided that severity is equal to or higher than -SeverityLevel. If -SeverityLevel is not specified or set to 0, Invoke-Sqlcmd returns 0 to ERRORLEVEL. The severity levels of Database Engine error messages range from 1 to 24. Invoke-Sqlcmd does not report severities for informational messages that have a severity of 10.

-SuppressProviderContextWarning <Boolean>

Suppresses the warning that Invoke-Sqlcmd has used the database context from the current SQLSERVER:SQL path setting to establish the database context for the cmdlet.

-Username <string>

Specifies the login ID for making a SQL Server Authentication connection to an instance of the Database Engine. The password must be specified using -Password. If -Username and -Password are not specified, Invoke-Sqlcmd attempts a Windows Authentication connection using the Windows account running the PowerShell session.When possible, use Windows Authentication.

-Variable <string[]>

Creates a sqlcmd scripting variable for use in the sqlcmd script, and sets a value for the variable. Use a PowerShell array to specify multiple variables and their values.


This cmdlet supports the common parameters: Verbose, Debug,ErrorAction, ErrorVariable, WarningAction, WarningVariable,OutBuffer, PipelineVariable, and OutVariable.




Formatted table

  1. This example connects to a named instance of the Database Engine on a computer and runs a basic Transact-SQL script:
    C:PS> Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputerMyInstance"
       5/13/2010 8:49:43 PM
  2. This example reads a file containing Transact-SQL statements and sqlcmd commands, runs the file, and writes the output to another file:
    C:PS> Invoke-Sqlcmd -InputFile "C:MyFolderTestSqlCmd.sql" | Out-File -filePath "C:MyFolderTestSqlCmd.rpt"
       Output sent to TestSqlCmd.rpt.

    Ensure all output files are secured with the appropriate NTFS permissions.

  3. This example uses an array of character strings as input to the -Variable parameter:
    C:PS> $MyArray = "MYVAR1='String1'", "MYVAR2='String2'"
    Invoke-Sqlcmd -Query "SELECT `$(MYVAR1) AS Var1, `$(MYVAR2) AS Var2;" -Variable $MyArray
       Var1                        Var2
       ----                        ----
       String1                     String2

    The array defines multiple sqlcmd variables. The $ signs in the SELECT statement that identify the sqlcmd variables are escaped using the back-tick (`) character.

  4. This example uses Set-Location to navigate to the SQL Server PowerShell provider path for an instance of the Database Engine:
    C:PS> Set-Location SQLSERVER:SQLMyComputerMyInstance
    Invoke-Sqlcmd -Query "SELECT SERVERPROPERTY('MachineName') AS ComputerName;" -ServerInstance (Get-Item .)
       WARNING: Using provider context. Server = MyComputer

    Then the example uses Get-Item to retrieve an SMO Server object for use as the -ServerInstance parameter of Invoke-Sqlcmd.

  5. This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command:
    C:PS> Invoke-Sqlcmd -Query "PRINT N'abc'" -Verbose
       VERBOSE: abc
  6. This examples uses a positional string to supply the input to the -Query parameter:
    C:PS> Set-Location SQLSERVER:SQLMyComputerDEFAULTDatabasesAdventureWorks2008R2
    Invoke-Sqlcmd "SELECT DB_NAME() AS DatabaseName;"
       WARNING: Using provider context. Server = MyComputer, Database = AdventureWorks2008R2.

    It also shows how Invoke-Sqlcmd uses the current path to set the database context to AdventureWorks2008R2.

Additional Notes