To run SQL commands from PowerShell, you use SQL Server PowerShell modules or the Invoke-Sqlcmd cmdlet (part of the SqlServer module), which lets you execute T-SQL scripts directly in the PowerShell environment. This is useful for automating database tasks like backups, schema updates, or data queries without opening SQL Server Management Studio (SSMS). You need SQL Server (or Azure SQL) access, PowerShell installed, and the SqlServer PowerShell module available.
What You'll Need
- PowerShell (version 5.1 or 7.0+; included with Windows, or install PowerShell 7+ separately)
- SQL Server instance (on-premises, VM, or Azure SQL Database) with appropriate permissions
- SqlServer PowerShell module (install via PowerShell Gallery)
- Valid SQL authentication: either Windows Authentication (for local/domain logins) or SQL login credentials (username/password)
- Network access to the SQL Server (firewall rules may need updating, especially for Azure SQL)
Step-by-Step
- Open PowerShell as Administrator (optional but recommended for module installation): Press
Win + Xand select Windows PowerShell (Admin) or Terminal (Admin) if using Windows Terminal. For non-admin tasks like running queries, standard user PowerShell may suffice. - Install the SqlServer module (if not already installed): Run the following command in PowerShell. This installs the module from the official PowerShell Gallery. You may be prompted to confirm installation (press
Ato allow all repositories if asked):
TheInstall-Module -Name SqlServer -Scope CurrentUser -Force-Scope CurrentUserensures it installs only for your user account, avoiding permission issues. If you need it system-wide, use-Scope AllUsers(requires admin rights). - Import the module: Even after installation, explicitly import it to ensure cmdlets like
Invoke-Sqlcmdare available:
To verify it loaded successfully, runImport-Module SqlServerGet-Command Invoke-Sqlcmd—you should see the cmdlet listed. - Prepare your SQL query and connection details: Write your T-SQL statement (e.g.,
SELECT * FROM Customers) and note the server name (e.g.,localhost\SQLEXPRESSoryourserver.database.windows.net), database name (e.g.,MyDatabase), and authentication method. - Run a simple query using Windows Authentication: If connecting to a local SQL Server instance with your Windows account:
This runs the query against theInvoke-Sqlcmd -Query "SELECT TOP 10 ProductName, ListPrice FROM Products" -ServerInstance "localhost\SQLEXPRESS" -Database "AdventureWorks2019"AdventureWorks2019database and displays results in the PowerShell console. - Run a query using SQL Authentication (with credentials): For SQL logins, store credentials securely and pass them:
$cred = Get-Credential Invoke-Sqlcmd -Query "SELECT @@VERSION" -ServerInstance "yourserver.database.windows.net" -Database "MyDB" -Credential $credGet-Credentialopens a dialog prompting for username (e.g.,admin@yourserver) and password. - Save results to a file (optional): Pipe output to
Export-CsvorOut-File:Invoke-Sqlcmd -Query "SELECT * FROM Orders" -ServerInstance "localhost" -Database "SalesDB" | Export-Csv -Path "C:\temp\orders.csv" -NoTypeInformation - Run a script from a .sql file: Use the
-InputFileparameter:Invoke-Sqlcmd -InputFile "C:\scripts\update_inventory.sql" -ServerInstance "localhost" -Database "InventoryDB"
Common Mistakes
- Module not imported: Skipping
Import-Module SqlServermay causeInvoke-Sqlcmdto be unrecognized. Always runGet-Command Invoke-Sqlcmdto verify. - Incorrect server name format: Named instances need backslash escaping (e.g.,
localhost\InstanceNamein quotes), not forward slashes. Azure SQL requires the full server name including.database.windows.net. - Authentication mismatch: Using
-Usernameand-Passwordparameters directly (deprecated in newer module versions). Instead, use-Credentialwith aPSCredentialobject. - Missing quotes around query strings: T-SQL queries with spaces or special characters must be in double quotes. Single quotes inside the query (e.g.,
WHERE Name = 'John') are fine, but the outer PowerShell string must be double-quoted. - Firewall blocking port 1433: Especially for Azure SQL or remote servers, ensure inbound/outbound rules allow traffic on TCP port 1433.
Tips
- Use variables for reusability: Define
$server,$db, and$queryat the top of your script to easily test different targets:$server = "localhost"; $db = "TestDB"; $query = "SELECT GETDATE() AS Now" Invoke-Sqlcmd -Query $query -ServerInstance $server -Database $db - Suppress verbose output: Add
-Verbose:$falseor redirect standard error to null (2>$null) to keep the console clean during automation. - Handle large result sets: For very large queries, use
-OutputSqlErrors $trueand-QueryTimeoutto control timeouts and capture errors:Invoke-Sqlcmd -Query "SELECT * FROM HugeTable" -ServerInstance "localhost" -Database "BigDB" -QueryTimeout 300 - Combine with other PowerShell tools: Pipe
Invoke-Sqlcmdoutput toWhere-ObjectorForEach-Objectfor filtering or formatting:Invoke-Sqlcmd -Query "SELECT Name, Price FROM Products" | Where-Object { $_.Price -gt 100 } - Use integrated security by default: When possible, prefer Windows Authentication over SQL logins for better security and simpler setup.
Troubleshooting
Here’s how to fix common issues:
- "The term 'Invoke-Sqlcmd' is not recognized": This means the SqlServer module isn’t loaded. Run
Get-Module -ListAvailable SqlServerto check if installed. If missing, reinstall withInstall-Module SqlServer -Force. If installed but not imported, runImport-Module SqlServerexplicitly. Restart PowerShell after installation. - "Login failed for user '...'": Verify credentials, server name, and database name. For Azure SQL, ensure the client IP is added to the server’s firewall rules (via Azure portal > SQL server > Connection strings > Show database connection strings for details). For on-premises, check if SQL Server Browser service is running for named instances.
- Connection timeout or "A network-related error occurred": Confirm the SQL Server is running (check Services on Windows:
services.mscfor SQL Server (MSSQLSERVER)). Test connectivity withTest-NetConnection -ComputerName yourserver -Port 1433. If using Azure SQL, ensure Allow Azure services and resources to access this server is enabled in Networking settings. - Query returns no results or errors silently: Add
-Verboseto see detailed logs. Use-ErrorAction Stopto force errors to display. Check for syntax issues in your T-SQL (e.g., missing semicolons in multi-statement scripts). - Module conflicts with older SQLPS module: If both
SQLPSandSqlServerare installed, conflicts may arise. Uninstall the legacySQLPSmodule viaUninstall-Module -Name SQLPS -AllVersions(if confirmed unused) and reinstallSqlServer.
Frequently Asked Questions
Can I run SQL commands on Azure SQL Database from PowerShell?
Yes—use the sameInvoke-Sqlcmd cmdlet with the full Azure server name (e.g., myserver.database.windows.net) and SQL authentication credentials. Ensure your client IP is whitelisted in Azure SQL’s firewall settings.
Do I need SQL Server Management Studio (SSMS) installed?
No. SSMS is not required. The SqlServer module works independently and is the recommended modern approach. (The olderSQLPS module bundled with SSMS is deprecated.)
Can I schedule SQL commands to run automatically?
Yes. Save your PowerShell script (e.g.,run_query.ps1) and use Windows Task Scheduler to run it on a timer. Ensure the scheduled task runs under a user account with database permissions.
Is it safe to store SQL credentials in scripts?
Avoid hardcoding passwords. UseGet-Credential at runtime, or store credentials securely in Windows Credential Manager and retrieve them via PowerShell (e.g., using Get-StoredCredential from the Security module). For production, consider managed identities (in Azure) or Azure Key Vault.
How do I pass parameters into my SQL query?
Use PowerShell variables and string interpolation, but always sanitize inputs to prevent SQL injection. For example:$name = "John".Replace("'", "''") # Escape single quotes
Invoke-Sqlcmd -Query "SELECT * FROM Users WHERE Name = '$name'" -ServerInstance "localhost"
For better safety, use parameterized queries via System.Data.SqlClient classes (not Invoke-Sqlcmd), which supports @parameter syntax.
Can I run multiple SQL statements in one command?
Yes. Separate statements with semicolons in the-Query parameter (e.g., "INSERT INTO Log...; UPDATE Users..."). However, Invoke-Sqlcmd returns results only from the final SELECT statement. Use -OutputSqlErrors $true to capture errors from all statements.