在 PowerShell 中返回 DataRow 的行数 [英] Returning a Row Count for a DataRow in PowerShell
问题描述
我的脚本正在从 SQL Server 中的存储过程填充数据行.然后我在整个脚本中引用此数据行中的特定列.我想要做的是添加功能,如果行数 = 0,则采取行动 X,如果行数 = 1,则采取行动 Y,如果行数 > 1,则采取行动 Z.
My script is populating a datarow from a stored procedure in SQL Server. I then reference specific columns in this datarow throughout the script. What I'm trying to do is add functionality that takes action X if the row count = 0, action Y if the row count = 1, and action Z if the row count > 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.
I can get $MyResult.Count to work if I'm using an array, but then I can't reference $MyRow.FileName directly.
这可能很简单,但我是 PowerShell 和面向对象语言的新手.我曾尝试搜索此站点、脚本专家的博客和 Google,但没有找到任何显示我如何执行此操作的内容.
This is probably pretty simple, but I'm new to PowerShell and object-oriented languages. I've tried searching this site, The Scripting Guy's blog, and Google, but I haven't been able to find anything that shows me how to do this.
非常感谢任何帮助.
推荐答案
看起来这个问题得到了很多意见,所以我想发布我是如何处理这个问题的.:)
Looks like this question gets a lot of views, so I wanted to post how I handled this. :)
基本上,我的修复方法是更改我用来在 SQL Server 上执行查询的方法.我切换到 Chad Miller 的 Invoke-SqlCmd2 脚本:TechNet:Invoke-SqlCmd2,即
Basically, the fix for me was to change the method I was using to execute a query on SQL Server. I switched to Chad Miller's Invoke-SqlCmd2 script: TechNet: Invoke-SqlCmd2, i.e.
# ---------------
# 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
}
这篇关于在 PowerShell 中返回 DataRow 的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!