简体   繁体   English

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

[英]Import data from SQL Server database to CSV using Powershell

Can anybody help me to rectify the error in the below script? 有人可以帮我纠正以下脚本中的错误吗? The error generated is 产生的错误是

Exception calling "Fill" with "1" argument(s): "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Loc ating Server/Instance Specified)" At SQLConnection.Ps1:11 char:17 + $SqlAdapter.Fill <<<< ($DataSet) 带有“ 1”自变量的异常调用“填充”:“建立与SQL Server的连接时发生与网络相关或特定于实例的错误。找不到服务器或无法访问该服务器。请验证实例名称是否正确并且该SQL Server已配置为允许远程连接。(提供者:SQL网络接口,错误:26-错误指定了服务器/实例的位置)“在SQLConnection.Ps1:11 char:17 + $ SqlAdapter.Fill <<<<( $ DataSet)

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

Script: 脚本:

$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() 
$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM