2015-03-19 219 views
0

任何人都可以幫我糾正下面腳本中的錯誤嗎?所產生的誤差是使用Powershell將數據從SQL Server數據庫導入到CSV

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)

  • 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= [email protected]" 
$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() 
+0

不知道這是很重要的,但我一直只看到 - 並用自己 - '「的uid = ...; PWD = ...「在連接字符串中。 – silent 2015-03-19 07:44:09

回答

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 
相關問題