Query Microsoft SQL Server with PowerShell: SELECT, Parameters, Invoke-Sqlcmd and CSV Export
· UpdatedVideo walkthrough (ran against a live database): https://youtu.be/VZycEzeXKXs
PowerShell can talk to Microsoft SQL Server directly, which makes it handy for reports, health checks and admin scripts that need data without opening SQL Server Management Studio. This guide covers the two common ways to do it: the .NET SqlClient classes, which work on any Windows box with no extra modules, and Invoke-Sqlcmd from the SqlServer module, which is shorter to write. It then covers parameters, logins, encryption and exporting results.
The Classic Way: System.Data.SqlClient
This is the script from the video. It uses .NET classes that ship with Windows PowerShell 5.1, so nothing needs installing:
$SqlQuery = @"
SELECT *
FROM TB_TEST
"@
$DataBaseName = "TESTING"
$SQLConnection = New-Object System.Data.SqlClient.SqlConnection
$SQLConnection.ConnectionString = "Server=localhost;Database=$DataBaseName;Integrated Security=SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SQLConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0]
What each piece does:
SqlConnectionholds the connection string: which server, which database, and how to authenticate.Integrated Security=SSPImeans "log in as the Windows user running this script".SqlCommandis the SQL you want to run, tied to that connection.SqlDataAdapteropens the connection, runs the command, fills aDataSetwith the results, and closes the connection again.$DataSet.Tables[0]is the first result set, which PowerShell displays as a table.
$SqlAdapter.Fill() returns the number of rows it loaded, which is why a number appears in the output before the table. Pipe it to Out-Null if you don't want it: $SqlAdapter.Fill($DataSet) | Out-Null.
Connecting to a Named Instance or Remote Server
The Server= part of the connection string decides where you connect:
| Target | Connection string value |
|---|---|
| Default instance on this machine | Server=localhost |
| Named instance (e.g. SQL Express) | Server=localhost\SQLEXPRESS |
| Remote server, default port | Server=sql01.corp.example.com |
| Remote server, custom port | Server=sql01.corp.example.com,14330 |
For remote servers, the SQL Server port (1433 by default) has to be open in the server's firewall, and the instance has to allow TCP/IP connections in SQL Server Configuration Manager.
Using a SQL Login Instead of Windows Authentication
If the server uses SQL authentication, don't hard-code the password in the script. Prompt for it with Get-Credential and build the connection with SqlCredential, which keeps the password out of the connection string:
$cred = Get-Credential -Message "SQL login for sql01"
$cred.Password.MakeReadOnly()
$sqlCred = New-Object System.Data.SqlClient.SqlCredential($cred.UserName, $cred.Password)
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=sql01.corp.example.com;Database=TESTING;"
$conn.Credential = $sqlCred
For unattended scripts, run them as a service account with Windows authentication rather than storing a SQL password at all.
Passing Parameters Safely
Never build a query by pasting user input or variables into the SQL string. A value like ' OR 1=1 -- changes the meaning of the query (SQL injection). Use parameters instead; SQL Server receives the value separately from the SQL text:
$customerId = 42
$conn = New-Object System.Data.SqlClient.SqlConnection("Server=localhost;Database=TESTING;Integrated Security=SSPI;")
$cmd = $conn.CreateCommand()
$cmd.CommandText = "SELECT Id, Name, CreatedAt FROM dbo.Customers WHERE Id = @Id"
[void]$cmd.Parameters.Add("@Id", [System.Data.SqlDbType]::Int)
$cmd.Parameters["@Id"].Value = $customerId
$table = New-Object System.Data.DataTable
try {
$conn.Open()
$reader = $cmd.ExecuteReader()
$table.Load($reader)
}
finally {
$conn.Close()
}
$table | Format-Table -AutoSize
The try / finally block makes sure the connection is closed even if the query throws an error, so long-running scripts don't leak connections.
The Short Way: Invoke-Sqlcmd
The SqlServer module from the PowerShell Gallery wraps all of the above in one cmdlet. Install it once per user:
Install-Module SqlServer -Scope CurrentUser
Then a query is a single line:
Invoke-Sqlcmd -ServerInstance "localhost" -Database "TESTING" -Query "SELECT TOP (10) * FROM TB_TEST"
Invoke-Sqlcmd supports parameters through -Variable, which substitutes $(Name) placeholders in the query. Note that this is text substitution done by the cmdlet, not a true SQL parameter, so only use it with values you control. For user-supplied input, use the SqlClient parameter example above.
Put the query in single quotes (or a single-quoted here-string) so PowerShell doesn't try to expand $(Status) itself before the cmdlet sees it:
$query = @'
SELECT * FROM TB_TEST WHERE Status = '$(Status)'
'@
Invoke-Sqlcmd -ServerInstance "localhost" -Database "TESTING" -Query $query -Variable "Status=Active"
Encryption errors with newer versions
Version 22 and later of the SqlServer module encrypt connections by default and check the server's certificate. Against a server with a self-signed certificate (common in labs and on SQL Express) you'll see a certificate trust error. The right fix is a trusted certificate on the server. In a lab you can tell the client to accept the existing one:
Invoke-Sqlcmd -ServerInstance "localhost" -Database "TESTING" -Query "SELECT 1" -TrustServerCertificate
Don't use -TrustServerCertificate against production servers across untrusted networks, because it means the client can't tell whether it's talking to the real server.
Exporting Results
Query results are ordinary PowerShell objects, so the usual cmdlets work on them.
To CSV, for Excel or another script:
Invoke-Sqlcmd -ServerInstance "localhost" -Database "TESTING" -Query "SELECT * FROM TB_TEST" |
Export-Csv -Path "C:\Reports\tb_test.csv" -NoTypeInformation -Encoding UTF8
To JSON, for an API or a web page:
$DataSet.Tables[0] | Select-Object * -ExcludeProperty RowError, RowState, Table, ItemArray, HasErrors |
ConvertTo-Json -Depth 3 | Set-Content "C:\Reports\tb_test.json" -Encoding UTF8
The -ExcludeProperty list drops the internal DataRow properties that would otherwise clutter the output when exporting results from the SqlClient approach.
Running It on a Schedule
To run a report every morning, save the script (for example C:\Scripts\daily-report.ps1) and register a scheduled task that runs as a service account with read access to the database:
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File C:\Scripts\daily-report.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 7am
Register-ScheduledTask -TaskName "Daily SQL report" -Action $action -Trigger $trigger -User "CORP\svc-sqlreport" -Password (Read-Host "Service account password")
Give that account only the permissions the report needs, typically db_datareader on one database, not sysadmin.
Troubleshooting
| Error | Usual cause |
|---|---|
A network-related or instance-specific error occurred |
Wrong server or instance name, TCP/IP disabled, SQL Browser stopped (named instances), or port 1433 blocked |
Login failed for user |
The Windows or SQL account has no login on the server or no access to that database |
Cannot open database "X" requested by the login |
The login exists but isn't mapped to that database |
The certificate chain was issued by an authority that is not trusted |
Encrypted connection to a server with a self-signed certificate; see the encryption section above |
Invalid object name |
Table name typo or wrong schema; try the full name, e.g. dbo.TB_TEST |
Quick Reference
| Task | Snippet |
|---|---|
| Windows auth connection string | Server=localhost;Database=DB;Integrated Security=SSPI; |
| Named instance | Server=localhost\SQLEXPRESS |
| Custom port | Server=host,14330 |
| One-line query | Invoke-Sqlcmd -ServerInstance host -Database DB -Query "SELECT 1" |
| Install module | Install-Module SqlServer -Scope CurrentUser |
| Export to CSV | Pipe results to Export-Csv out.csv -NoTypeInformation |