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 the bcp command-line utility


This recipe shows how to export contents of a table to a CSV file using PowerShell and bcp.

Getting ready

Make sure you have access to the AdventureWorks2014 database. We will export the Person.Person table to a pipe (|) delimited, timestamped text file.

Create a C:\Temp\Exports folder, if you don't already have it in your system.

How to do it...

These are the steps to perform bulk export using bcp:

  1. Open PowerShell ISE as administrator.

  2. Add the following script and run:

    $server = "localhost"
    $table = "AdventureWorks2014.Person.Person"
    $curdate = Get-Date -Format "yyyy-MM-dd_hmmtt"
    
    $foldername = "C:\Temp\Exports\"
    
    #format file name
    $formatfilename = "$($table)_$($curdate).fmt"
    
    #export file name
    $exportfilename = "$($table)_$($curdate).csv"
    
    $destination_exportfilename = "$($foldername)$($exportfilename)"
    $destination_formatfilename = "$($foldername)$($formatfilename)"
    
    #command to generate format file
    $cmdformatfile = "bcp $table format...