2014-10-02 56 views
0

下面是我創建的用於返回表格的PowerShell函數。PowerShell函數返回列表視圖中的表格

  function GetJOINConstraints 
     { 
     [CmdletBinding()] 
      param(
      [Parameter(Mandatory=$true)] $ConnectionString, 
      [Parameter(Mandatory=$true)] $tableName 
       ) 

     $Conn = new-object System.Data.SqlClient.SQLConnection 
     $Conn.connectionString=$ConnectionString 
     $Conn.Open() 
     $Cmd = New-Object System.Data.SqlClient.SqlCommand 
     $Cmd.Connection = $Conn 
     $cmd.CommandText = "Exec TemplateTransport.usp_Get_JOINConstraints 'Action'" 
     #$Cmd.CommandType = [System.Data.CommandType]'StoredProcedure' 
     #$Cmd.Parameters.Add("@TargetTableName", $tableName) 
     $SQLAdapter = New-Object System.Data.Sqlclient.SqlDataAdapter 
     $SqlAdapter.SelectCommand = $Cmd 
     $rs = New-Object System.Data.DataSet 
     $SqlAdapter.Fill($rs) 
     Return $rs.Tables[0] | Format-Table 
     $Con 

    n.Close() 

} 

當我嘗試運行這個函數返回的結果類似下面

fkeyid : Action 
fkeycol : ActionTypeID 
fkeynull : False 
rkeyid : ActionType 
rkeycol : ID 
nkcol : Name 
alias : 
nullable : False 
fkOrder : 1 

fkeyid : Action 
fkeycol : DefaultTimeTrackingTaskID 
fkeynull : True 
rkeyid : TimeTrackingTask 
rkeycol : ID 
nkcol : Name 
alias : 
nullable : True 
fkOrder : 1 

我正在尋找一個類似的結果

fkeyid fkeycol fkeynull rkeyid rkeycol nkcol alias nullable fkOrder 
------ ------- -------- ------ ------- ----- ----- -------- ------- 
Action Actio... False Actio... ID  Name     False  1 
Action Defau...  True TimeT... ID  Name     True  1 
Action Proce... False Process ID  Proce... Proce... False  1 
Action TimeT...  True TimeT... ID  Name     True  1 

我能做到,使用Format-Table。但不能將結果集保存到數組中。我希望能夠將它保存到一個數組並對其進行處理。任何幫助深表感謝。

謝謝。

回答

5

您應避免將輸出的文本格式化爲函數的返回值。有什麼更好的用途是完全刪除該行,將輸出存儲到變量中,然後將該變量傳遞給format-table。所以,從你的函數刪除|Format-Table,然後做這樣的事情:

$TableJoins = GetJOINConstraints -ConnectionString $ConString -TableName $tblName 
$TableJoins | Format-Table 

或者您可以使用Tee-Object來輸出存入一個變量,仍管它格式表:

GetJOINConstraints -ConnectionString $ConString -TableName $tblName | Tee-Object -Variable TableJoins | Format-Table 
+0

我想將結果集保存到一個數組並循環訪問數組。所以我試過[數組] $ dt = GetJOINConstraints -ConnectionString $ ConnString -tableName $ tableName1但是當我嘗試獲取$ dt [1] [2]它說無法索引到類型system.Int32 – Avinash 2014-10-03 14:31:26

+1

對象您是否期待數組數組?你不想做'$ dt [1] .fkeynull'嗎? – TheMadTechnician 2014-10-03 14:51:13

+0

我是Powerhell的新手。我期待着一個2D陣列。具有不同Sproc的類似函數返回一個2d數組。但我相信我可以使用$ dt [1] .fkeynull。謝謝。我會及時向大家發佈。 – Avinash 2014-10-03 14:55:00