PowerShell: Invoke-SqlCmd
Author: jason
Date: 2019-05-04 09:41:55
Category: Technical

PowerShell can be configured to run SQL commands. And it's pretty easy to do so... Join the fun!

Normally I am running PowerShell on the same server where SQL is already installed. When that isn't the case, I have been able to install at least SQL Server Management Studio, which is free. But if you can't even do that, you can try just installing the bare PowerShell SQL modules. There are even instructions on how to install the module when you aren't an Administrator (use -Scope CurrentUser).

Code

Install-Module -Name SqlServer


And now you can run a Query!
Code

$results = Invoke-Sqlcmd -Query 'SELECT * FROM dbo.ExampleTable' `
-ServerInstance '.\SQL2017' `
-Database 'Usage' `
-ConnectionTimeout 60 `
-QueryTimeout 300 `
-ErrorAction continue




Installing the PowerShell SQL Module
https://docs.microsoft.com/en-us/sql/powershell/download-sql-server-ps-module?view=sql-server-2017

Using the Invoke-SqlCmd
https://docs.microsoft.com/en-us/powershell/module/sqlserver/invoke-sqlcmd?view=sqlserver-ps





jason @ jasonthomasfrance.com - www.masterstationlog.com - copyright 2009