2013-03-13 27 views
1

我的腳本正在SQL Server中的存儲過程中填充數據行。然後在整個腳本中引用此數據表中的特定列。我想要做的就是添加的功能,採取措施X如果行數= 0,動作Y如果行數= 1,並採取行動Z如果行計數> 1在PowerShell中返回DataRow的行數

-- PowerShell script snippet 

# $MyResult is populated earlier; 
# GetType() returns Name=DataRow, BaseType=System.Object 

# this works 
ForEach ($MyRow In $MyResult) { 

    $MyFile = Get-Content $MyRow.FileName 
    # do other cool stuff 
} 

# this is what I'm trying to do, but doesn't work 
If ($MyResult.Count -eq 0) { 
    # do something 
} 
ElseIf ($MyResult.Count -eq 1) { 
    # do something else 
} 
Else { 
    # do this instead 
} 

我能得到$ MyResult.Count工作,如果我使用一個數組,但然後我不能直接引用$ MyRow.FileName。

這可能很簡單,但我是PowerShell和麪向對象語言的新手。我試過搜索這個網站,腳本專家的博客和谷歌,但我一直沒有找到任何能夠告訴我如何做到這一點的東西。

任何幫助,非常感謝。

+2

檢查'$ MyResult | Get-Member'來查看對象提供的方法和屬性。 – 2013-03-13 20:31:35

+0

謝謝你回覆,Ansgar。我應該提到我查看過這些內容,並且發現可以執行$ MyResult.ItemArray.Count,但它返回了所有列和行的計數。因此,如果計算> 0,它無法找到計數是否爲1。 – sqlfool 2013-03-13 20:42:33

+0

$ MyResult.rows.Count是否有效? – FilamentUnities 2013-03-13 21:45:48

回答

0

看起來這個問題得到了很多意見,所以我想發佈我是如何處理這個問題的。 :)

基本上,我的修補程序是改變我用來在SQL Server上執行查詢的方法。我切換到Chad Miller的Invoke-SqlCmd2腳本:TechNet: Invoke-SqlCmd2,即

# --------------- 
# this code works 
# --------------- 

# Register the function 
. .\Invoke-Sqlcmd2.ps1 

# make SQL Server call & store results to an array, $MyResults 
[array]$MyResults = Invoke-Sqlcmd2 -Serve 
rInstance "(local)" -Query "SELECT TOP 1 * FROM sys.databases;" 

If ($MyResult -eq $null) { 
    # do something 
} 
ElseIf ($MyResult.Count -eq 1) { 
    # do something else 
} 
Else { 
    # do this instead 
} 
1

我沒有PS和SQL的經驗,但我會盡力爲您提供一個答案。如果你是對象$myresult是一個datarow對象,這意味着你只有一行。如果結果爲空,則$myresult通常爲空。

如果你得到一行或多行,你可以把它們放在一個數組中並對其進行計數。但是,如果您的$myresult爲空,並且將其放入數組中,它仍然會算作一個數,因此我們需要注意這一點。試試這個:

If ($MyResult -eq $null) { 
    # do something if no rows 
} 
Else If (@($MyResult).Count -eq 1) { 
    # do something else if there are 1 rows. 
    # The cast to array was only in the if-test, 
    # so you can reach the object with $myresult. 
} 
Else { 
    # do this if there are multiple rows. 
} 
1

它與你如何填充$MyResult有關。如果你喜歡查詢

$MyResult = @(<< code that returns results from database >>) 

是,封閉該內@(...)返回數據集/數據表從數據庫中,然後返回將是很容易的行數使用$MyResult.count檢查代碼數據庫。

如果以這種方式填充$ MyResult,您的原始代碼應該按原樣工作。

相關問題