Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Performing bulk export using Invoke-SqlCmd


This recipe shows 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 AdventureWorks2014 database. We will use the Person.Person table. Create a C:\Temp folder, if you don't already have it in your system.

How to do it...

Follow these steps to perform a bulk export using PowerShell and Invoke-sqlcmd:

  1. Open PowerShell ISE as administrator.

  2. 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 = "localhost"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run:

    #database handle
    $dbName = "AdventureWorks2014"
    $db = $server.Databases[$dbName]
    
    #export file name
    $exportfile = "C:\Temp\Person_Person.csv"
    
    $query = @"
    SELECT
       *
    FROM
       Person.Person
    "@
    Invoke-Sqlcmd -Query...