dbatools is a free PowerShell module with over 180 SQL Server administration, best practice and migration commands included.


Runs a T-SQL script. Invoke-Sqlcmd2 runs the whole script and only captures the first selected result set, such as the output of PRINT statements when -verbose parameter is specified.

Parameterized queries are supported.

Help details below borrowed from Invoke-Sqlcmd.


This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query.

Invoke-Sqlcmd2 -ServerInstance “MyComputer\MyInstance” -Query “SELECT login_time AS ‘StartTime’ FROM sysprocesses WHERE spid = 1”

This example reads a file containing T-SQL statements, runs the file, and writes the output to another file.

Invoke-Sqlcmd2 -ServerInstance “MyComputer\MyInstance” -InputFile “C:\MyFolder\tsqlscript.sql” | Out-File -filePath “C:\MyFolder\tsqlscript.rpt”

This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command.
VERBOSE: hello world

Invoke-Sqlcmd2 -ServerInstance “MyComputer\MyInstance” -Query “PRINT ‘hello world'” -Verbose


Changelog moved to CHANGELOG.md.


This command was created by a ton of community members, including Chad Miller and Warren Frame.


From PowerShell, execute Get-Help Invoke-Sqlcmd2 -Detailed for more information on this function.

Source Code

Want to see the source code? View Invoke-Sqlcmd2.ps1 on GitHub

Related commands