How to execute .sql file using powershell?
Execute a .sql
file with PowerShell using:
Replace script.sql
with your file, Server
with your SQL server, and DB
with your database name. Ensure the SqlServer
module is installed (Install-Module -Name SqlServer
).
Setting up your PowerShell Environment to Run SQL
Before launching your .sql
script through PowerShell, ensure your environment:
-
Snap-ins Check: Use
Get-PSSnapin -Registered
to see ifSqlServerCmdletSnapin100
andSqlServerProviderSnapin100
are there. If not, add them usingAdd-PSSnapin
. -
SQLPS Module for Later Versions: For SQL Server versions 2012 onwards, use the SQLPS or SqlServer module. Everything depends on the version you are having a date with.
-
2008 Snap-ins: If you are dealing with SQL Server 2008, snap-ins might be your only allies. Take up the effort to import them from the PowerShell Modules directory.
-
Go Direct with SqlConnection: As a direct and custom approach, use
System.Data.SqlClient.SqlConnection
along with theSqlCommand
class.
Executing with a Side of Control and Handling
Let's enhance and tune the command execution:
Fine-tuning Execution
Various parameters provide more control. Queue endless possibilities!
- QueryTimeout: Save your time or limit the script's time. Whoever comes first!
- ErrorAction 'Stop': Call it a day when there's an error.
- Verbose: Get yourself a detailed version of what's happening.
Mastering Error Management
Make use of try/catch/finally
blocks because you have the power!
Minimum but Efficient
Consider a non-module SQL execution:
Scripts Execution: Landmines and Golden Eggs
Double-check Connection String
Ensure your connection string is co-operating with the target database. Broken connection is bad for execution!
Snap-in/Module Updates
Your SQL snap-ins or modules need to roll with the times. Keep up with the SQL Server versions to avoid the ex'es problem.
Efficient Use of Variables
Use Set-Variable
for resource management. We all love resources, right?
Script Content Matters
Ensure your script won't bring nasty surprises in the middle of the run. Part-done jobs are uglier than no jobs!
Dealing with Permissions
Check that the doer (executing account) has the correct privileges. Always ask before touching, right?
Was this article helpful?