powershell 遍历数据库表导出为csv

Posted _iorilan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 遍历数据库表导出为csv相关的知识,希望对你有一定的参考价值。

Write-Output 0
$server = ".\\"
$database = "dbname"
$tablequery = "SELECT schemas.name as schemaName, tables.name as tableName from sys.tables inner join sys.schemas ON tables.schema_id = schemas.schema_id"
Write-Output 1
#Delcare Connection Variables
$connectionTemplate = "Data Source=0;Integrated Security=SSPI;Initial Catalog=1;"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
Write-Output 2
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $tablequery
$command.Connection = $connection
Write-Output 3
#Load up the Tables in a dataset
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()

# Loop through all tables and export a CSV of the Table Data
foreach ($Row in $DataSet.Tables[0].Rows)

    $queryData = "SELECT top 100 * FROM [$($Row[0])].[$($Row[1])]"

    #Specify the output location of your dump file
    $extractFile = "D:\\T\\Temp\\gmstableexport\\$($Row[0])_$($Row[1]).csv"

    $command.CommandText = $queryData
    $command.Connection = $connection

    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $command
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $connection.Close()

    $DataSet.Tables[0]  | Export-Csv $extractFile -NoTypeInformation

 

以上是关于powershell 遍历数据库表导出为csv的主要内容,如果未能解决你的问题,请参考以下文章

powershell PS SP将列表导出为CSV

powershell 将本地文件的属性导出为CSV文件。

powershell 此PowerShell脚本是从SCCM DB获取SCEP日志并将其导出为CSV文件

powershell 将所有组中的所有术语集导出为CSV文件。

SwiftUI - 将核心数据导出到 CSV 文件 - 无法遍历实体

powershell 功能 - 数据 - UI:将数据网格导出到CSV文件