Performing bulk export using Invoke-Sqlcmd
This recipe
demonstrates how to export contents of a table to a CSV file using PowerShell and the
Invoke-Sqlcmd
cmdlet.
Getting ready
Make sure you have access to the AdventureWorks2008R2
database. We will use the Person.Person
table.
Create a C:\Temp
folder, if you don't already have one on your system.
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:
#database handle $dbName = "AdventureWorks2008R2" $db = $server.Databases[$dbName] #export file name $exportfile = "C:\Temp\Person_Person.csv" $query = @" SELECT * FROM Person.Person "@ Invoke...