Your weekly sales numbers live in SQL Server, and you’re tired of opening SQL Server Management Studio just to copy them into a spreadsheet. PowerShell can ask the database directly and hand the rows back as objects.
Quick answer: use Invoke-Sqlcmd from the SqlServer module to run a SQL query in PowerShell. Give it the server with -ServerInstance, the database with -Database and the T-SQL text with -Query:
Invoke-Sqlcmd -ServerInstance '(localdb)\MSSQLLocalDB' -Database SalesDemo `
-Query 'SELECT OrderId, Customer, City, Amount FROM dbo.Orders'
Output:
OrderId Customer City Amount
------- -------- ---- ------
1001 Maria Lopez Austin 1250.000
1002 Tom Baker Denver 450.000
1003 Dana Reyes Seattle 899.990
1004 Alex Wilber Austin 75.500
1005 Megan Bowen Boston 2310.400
In this tutorial, we’ll use Invoke-Sqlcmd to run SQL queries from PowerShell against a real database: installing the module, SELECT and UPDATE statements, .sql files, sqlcmd variables, CSV exports, error handling, and the encryption change in module version 22.
What You Need Before You Start
You need PowerShell 7 or Windows PowerShell 5.1, the SqlServer module from the PowerShell Gallery, and a SQL Server you can sign in to with your Windows account. Not sure which instances exist on your network? You can find SQL Server instances with PowerShell first.
For this guide we used SQL Server 2019 Express LocalDB, the free developer edition that ships with Visual Studio. Its instance name is (localdb)\MSSQLLocalDB, and every command below works the same against a full SQL Server.
We built a demo database called SalesDemo with one table, dbo.Orders, holding five orders from Austin, Denver, Seattle and Boston. Amounts are in USD, and all dates are in October 2026.
Step 1: Install the SqlServer Module
Invoke-Sqlcmd isn’t built into PowerShell. Microsoft ships it in the SqlServer module, and SQL Server Management Studio doesn’t install it for you. Run this once in each shell you use:
Install-Module -Name SqlServer -Scope CurrentUser
-Scope CurrentUser installs it for your account only, so you don’t need an elevated window. If Install-Module itself fails, see how to fix Install-Module is not recognized.
Then confirm the version, because the encryption behavior changed in version 22:
"Commands in the module: $((Get-Command -Module SqlServer).Count)"
Get-Module -ListAvailable -Name SqlServer | Select-Object -Property Name, Version
Output in PowerShell 7:
Commands in the module: 97
Name Version
---- -------
SqlServer 22.4.5.1
Both shells loaded SqlServer 22.4.5.1, but Windows PowerShell 5.1 listed 100 commands and PowerShell 7 only 97. The three extra ones are availability group tests (Test-SqlAvailabilityGroup and friends) that the module exposes only in 5.1.
Invoke-Sqlcmd itself is in both. You can also list every installed PowerShell module to spot an old SQLPS copy.