使用Powershell将数据从SQL Server数据库导入CSV

时间:2015-03-19 07:19:32

标签: sql sql-server powershell

有人可以帮我纠正下面脚本中的错误吗?产生的错误是

  

异常通话"填写"用" 1"参数:"建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。 (提供者:SQL网络接口,错误:26 - 错误Loc   ating Server / Instance Specified)"在SQLConnection.Ps1:11 char:17 + $ SqlAdapter.Fill<<<< ($数据集)

     
      
  • CategoryInfo:NotSpecified:(:) [],MethodInvocationException
  •   
  • FullyQualifiedErrorId:DotNetMethodException
  •   

脚本:

$SQLServer = "SQC1S02.domain.net\sqlvs06"
$SQLDBName = "User_prd"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database =    $SQLDBName; User ID= Domain\User9; Password= Password@123" 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) 
$DataSet.Tables[0] | out-file "Output.csv"
$SqlConnection.Close() 

1 个答案:

答案 0 :(得分:0)

$SQLServer   = "SQC1S02.domain.net\sqlvs06"
$SQLDBName   = "User_prd"
$user        = "Domain\UserName"
$pwd         = "Password"
$extractFile = "Output.csv"
$SQLDBQuery  = "SELECT * FROM SQLTableName"

$connectionTemplate = "Data Source={0};uid=$user;pwd=$pwd;Integrated Security=true;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $SQLServer, $SQLDBName)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $SQLDBQuery
$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