Executing a query / SQL script
This recipe shows how you can execute either a hardcoded query or a SQL script, from PowerShell.
Getting ready
Create a file in your C:\Temp
folder called SampleScript.sql
. This should contain:
SELECT * FROM Person.Person
How to do it...
Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.
Import the
SQLPS
module, and create a new SMO Server object:#import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
Add the following script and run it:
$dbName = "AdventureWorks2008R2" $db = $server.Databases[$dbName] #execute a passthrough query, and export to a CSV file Invoke-Sqlcmd ` -Query "SELECT * FROM Person.Person" ` -ServerInstance "$instanceName" ` -Database $dbName | Export-Csv -LiteralPath "C:\Temp\ResultsFromPassThrough.csv" ` ...