2012-01-04 67 views
2

我在從SQL Server中的簡單存儲過程中獲取數據時遇到了一些困難。我有一個Powershell腳本,需要從3列填充變量(該過程只返回1行)使用Powershell從SQL Server 2008獲取數據

這是我沒有工作。不知何故,我沒有正確引用列值。我嘗試了各種方法,但通常會出現錯誤「無法索引到空數組」。我不想通過ResultSet迭代,我只是想直接設置一些值從一行返回到變量

$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection 
$conn.ConnectionString = ` 
    "Server=ServerName;Database=ShopDB;Integrated Security=True" 
$sqlQuery = new-object System.Collections.Specialized.StringCollection 
$sqlQuery.Add("JobSettingsGet") 
$Resultset = $conn.ExecuteWithResults($sqlQuery) 

# $UserName = $table.Rows(0).Columns(0) 
    # error - Method invocation failed because [System.Data.DataTable] doesn't 
    # contain a method named 'Rows'. 
# $UserName = $table.Rows[0].Columns[0] 
    # error - cannot index null array 
# $UserName = $table.Row(0).Column(0) 
    # error - Cannot index into a null array, also Method invocation failed 
    # because [System.Data.DataTable] doesn't contain a method named 'Row'. 
# $UserName = $table.Rows[0].Columns[1].Value 
    # error - cannot index null array 

我想如果可能的話使用的列名了。

任何指針?

感謝, 西爾維亞

回答

5

你可以使用System.Data.SqlClient.SqlConnection代替SqlServer.Management

$conn = New-Object Data.Sqlclient.Sqlconnection` 
    ("Data Source=DATABASE;Initial Catalog=master;Integrated Security=SSPI;") 
$adapter = New-Object Data.Sqlclient.Sqldataadapter("exec sp_who2", $conn) 
$set = new-object data.dataset 
$adapter.fill($set) 
$table = new-object data.datatable 
$table = $set.tables[0] 

爲了打印整個表,只需使用format-table

$table | ft -AutoSize 

若要獲得列名稱,使用foreach迭代器並按名稱訪問說明屬性

$table | % {$_.login} 

Ed:這是通過使用SqlServer.Management相同的查詢。

[void][Reflection.Assembly]::LoadWithPartialName` 
    ("Microsoft.SqlServer.ConnectionInfo") 
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection 
$conn.ConnectionString = ` 
    "Server=ServerName;Database=ShopDB;Integrated Security=True" 
$sqlQuery = new-object System.Collections.Specialized.StringCollection 
$sqlQuery.Add("exec sp_who2") 
$resultset = $conn.ExecuteWithResults($sqlQuery) 

訪問結果由名採摘第零結果集,第零表,第零行和項目

$resultset[0].tables.Item(0).Rows[0].Item("Login") 
+0

感謝您的信息。我可以連接到數據庫,並使用foreach迭代器工作。但是,我想要做的是(因爲我知道只有1行和3列)將實際數據轉化爲變量而不進行迭代。像下面的東西(它給出錯誤「無法索引到一個空數組」): $ UserName = $ table.rows [0] .columns [0] – Sylvia 2012-01-05 09:35:53

+0

$ table.rows [0]應該是System.Data。沒有Columns成員的DataRow。嘗試使用item()方法:$ table.Rows [0] .item(「Login」)。 – vonPryz 2012-01-05 10:13:52

+0

謝謝,它現在有效。任何有關何時最好使用sqldataadapter而不是其他數據訪問方法(ExecuteWithResults等)的評論 – Sylvia 2012-01-05 13:06:34