在PowerShell中返回DataRow的行计数

时间:2013-03-13 20:11:59

标签: powershell powershell-v3.0

我的脚本正在填充SQL Server中存储过程的数据行。然后,我在整个脚本中引用此数据行中的特定列。我想要做的是添加功能,如果行计数= 0则采取动作X,如果行计数= 1则采取动作Y,如果行数> 1则采取动作Z. 1.

-- 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和面向对象语言的新手。我试过搜索这个网站,The Scripting Guy的博客和Google,但我找不到任何能告诉我如何做到这一点的内容。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:3)

它与您填充$MyResult的方式有关。如果您像

那样查询数据库
$MyResult = @( << code that returns results from database >> )

也就是说,在@( ... )中包含从数据库返回数据集/数据表的代码,然后使用$MyResult.count可以轻松检查返回的行数。

如果以这种方式填充$ MyResult,原始代码应该按原样运行。

答案 1 :(得分:1)

我没有PS和SQL的经验,但我会尽力为您提供答案。如果您的对象$myresultdatarow - 对象,则表示您只获得了一行。如果结果为空,则$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.
}

答案 2 :(得分: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
}

答案 3 :(得分:0)

我知道此线程很旧,但是如果其他人在Google上找到了它,则该线程也可以在PS V5上运行:

$MyResult.Count替换为($MyResult | Measure-Object | select -ExpandProperty Count)

例如:
If (($MyResult | Measure-Object | select -ExpandProperty Count) -eq 0)