Powershell Script to export/import SQL Server tables

Frank Anellia 41 Reputation points
2021-02-22T19:53:35.477+00:00

Hello,

I'm looking to automate a SQL Server export/import job. The tables are located on Azure SQL Server so I was thinking of using a PS script for automation purposes. The job will run on a monthly basis to copy files from a few tables in one database to the same tables into a database on a different server.

I'm looking for a starting point, and was having trouble finding anything online.

Any help would be greatly appreciated.

Thanks,
Frank

Azure SQL Database
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,997 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,424 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,570 questions
{count} votes

Accepted answer
  1. AmeliaGu-MSFT 13,961 Reputation points Microsoft Vendor
    2021-02-23T05:57:17.577+00:00

    Hi FrankAnellia-9381,

    You can try to use SqlBulkCopy with Powershell to copy data from tables in one database to the same tables into a database on a different server. Please refer to this article which might help.
    You also can use powershell dbatools Copy-DbaDbTableData to copy data.
    For example, to copy all the data from table dbo.test_table (2-part name) in database dbatools_from on sql1 to table test_table in database dbatools_from on sql2:

    Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table dbo.test_table  
    

    Please refer to Copy-DbaDbTableData for more details.

    Best Regards,
    Amelia


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Rich Matheisen 45,266 Reputation points
    2021-02-22T20:43:56+00:00

    Google.
    powershell sql server import
    powershell sql server export


  2. Jeffrey Williams 1,891 Reputation points
    2021-02-22T21:04:56.417+00:00

    You can start with Invoke-SqlCmd - something like:

    $sourceData = Invoke-SqlCmd -ServerInstance ... -Query "...";
    

    You can then pipe that to Export-Csv to create a CSV file.

    Then use BCP or BULK INSERT on the destination to read in the CSV file.