有沒有一種方法可以保存sql連接的詳細信息並在同一個腳本中重新使用它們。我寫了下面的內容,將3個sql表的內容導出到同一個數據庫中。它的工作原理,但它重新使用一個代碼的負載,我不知道如何減少它。在PowerShell中存儲並重新使用sql連接字符串
我試過聲明所有的連接信息,然後說明它現在的完整代碼的位置,但只輸出第一個表3次。
我也試過說過一次在開始時再次沒有工作。
#agent_lookup
$server = "test"
$database = "MI_Lookups"
$query = "EXEC [dbo].[proc_update_new_agents]
SELECT [l].agent_key AS 'Agent_Key'
,ISNULL([l].agent_name,'') AS 'Agent_Name'
,ISNULL([l].agent_name_1,'') AS 'Agent_Name_1'
,ISNULL([l].agent_type,'') AS 'Agent_Type'
FROM [dbo].[agent_test] AS [l]
ORDER by [l].agent_key asc"
$connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database;")
$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-Csv $saveloaction\"Agent_Lookup.csv"
$connection.Close()
#organisation_lookup
$server = "test"
$database = "MI_Lookups"
$query = "EXEC [dbo].[proc_update_new_organisations]
SELECT [l].organisation_key AS 'Organisation_Key'
,ISNULL([l].broker_name,'') AS 'Broker_Name'
,ISNULL([l].team_member,'') AS 'Team_Member'
,ISNULL([l].team_leader,'') AS 'Team_Leader'
FROM [dbo].[orgnisation_test] as [l]
ORDER BY [l].organisation_key asc"
$connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database;")
$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-Csv $saveloaction\"Organisation_Lookup.csv"
$connection.Close()
#insurer_lookup
$server = "test"
$database = "MI_Lookups"
$query = "EXEC [dbo].[proc_update_new_insurers]
SELECT [l].insurer_key AS 'Insurer_Key'
,ISNULL([l].insurer_name,'') AS 'Insurer_Name'
,ISNULL([l].insurer_name_1,'') AS 'Insurer_Name_1'
,ISNULL([l].team_member,'') AS 'Team_Member'
,ISNULL([l].team_leader,'') AS 'Team_Leader'
FROM [dbo].[insurer_test] AS [l]
ORDER BY [l].insurer_key asc"
$connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$server;Integrated Security=SSPI;Initial Catalog=$database;")
$command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-Csv $saveloaction\"Insurer_Lookup.csv"
$connection.Close()
這似乎是合乎邏輯的我只需要編寫一次的連接信息,但我是新來的PowerShell和努力,使這個簡單,我敢肯定,也是應該的。以上是基本相同的腳本重複三次與不同的表引用。
一如既往的感謝。
天才!我能夠完美地實現這一點。我甚至設法在腳本的另一個元素中重新使用try/catch,並將結果附加到日誌文件中。謝謝。 – chris1982 2015-03-04 09:11:22