我的脚本是从SQL Server中的存储过程填充数据行。然后,我在整个脚本中引用此数据行中的特定列。我想要做的是添加功能,如果行计数= 0,则执行操作X,如果行计数= 1,则执行操作Y,如果行计数> 1,则执行操作Z.
-- 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的博客和谷歌,但我找不到任何能告诉我如何做到这一点的内容。
任何帮助深表感谢。
它与你如何填充$MyResult
有关。如果你查询数据库就好
$MyResult = @( << code that returns results from database >> )
也就是说,在@( ... )
中包含从数据库返回数据集/数据表的代码,然后使用$MyResult.count
可以轻松检查返回的行数。
如果以这种方式填充$ MyResult,原始代码应该按原样运行。
我没有PS和SQL的经验,但我会尽力为你提供答案。如果你是对象$myresult
是一个datarow
对象,它意味着你只有一行。如果结果为空,那么$myresult
通常为空。
如果您获得一行或多行,则可以将它们放入数组中并对其进行计数。但是,如果你的$myresult
为null,并且你把它放在一个数组中它仍然算作一个,所以我们需要注意这一点。试试这个:
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.
}
看起来这个问题有很多观点,所以我想发布我是如何处理这个问题的。 :)
基本上,我的修复是更改我用于在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
}
我知道这个帖子已经过时了,但是如果有其他人在Google上找到它,那么它也适用于PS V5:
将$MyResult.Count
替换为:($MyResult | Measure-Object | select -ExpandProperty Count)
例如:
If (($MyResult | Measure-Object | select -ExpandProperty Count) -eq 0)