SQL 在 powershell 中从 System.Data.DataRow 中提取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39224692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract data from System.Data.DataRow in powershell
提问by cyberbemon
I have a powershell script that executes an sql command and returns a list of ID numbers.
我有一个执行 sql 命令并返回 ID 号列表的 powershell 脚本。
When I iterate through the list, this is what it returns.
当我遍历列表时,这就是它返回的内容。
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
I tried adding Out-String
to my list,
我尝试添加Out-String
到我的列表中,
$q_result = $db.ExecuteWithResults($int_cmd2)
$table = $q_result.Tables[0] | Out-String
foreach ($user_info in $table)
{
write-host $user_info
}
but that returns a poorly formatted list of numbers, everything is tabbed to the very right. see below.
但这会返回一个格式错误的数字列表,所有内容都在最右边。见下文。
GroupID
-------------
381
382
383
384
385
386
I tried using, $user_info.Item[0]
in the loop, but that returns nothing.
我尝试$user_info.Item[0]
在循环中使用,但没有返回任何内容。
How can I extract just the numbers from the list?.
如何仅从列表中提取数字?
回答by Mathias R. Jessen
Item
is a parameterized property, not a list you can index into:
Item
是一个参数化的属性,而不是一个可以索引的列表:
foreach($row in $table)
{
$row.Item("GroupID")
}
or (assuming that "GroupID" is the first column):
或(假设“GroupID”是第一列):
foreach($row in $table)
{
$row.Item(0)
}
回答by Nyagolova
回答by Dominic Flynn
Assuming the column name is GroupID
假设列名是 GroupID
$sql = "SELECT [GroupID] FROM theTable"
$table = Invoke-SQLCmd -Query $sql -ServerInstance $sqlServerInstance -Database $database -OutputAs DataRows
foreach($user_info in $table)
{
$user_info.GroupID
}
or
或者
foreach($user_info in $table.GroupID)
{
$user_info
}