PowerShell 函数中返回 DataSet/DataTable 的奇怪行为 [英] Strange behavior in PowerShell function returning DataSet/DataTable

查看:35
本文介绍了PowerShell 函数中返回 DataSet/DataTable 的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我发疯.我有一个来自多个脚本的库,其中包含以下功能:

This is driving me crazy. I have a library I source from multiple scripts, which contains the following function:

function lib_open_dataset([string] $sql) {
    $ds = new-object "System.Data.DataSet"
    $da = new-object "System.Data.SqlClient.SqlDataAdapter" ($sql, $_conn_string)

    $record_count = $da.Fill($ds)

    return $ds
}

这几乎在任何地方都被调用,它工作得很好,除了我通常必须这样做:

This is called pretty much everywhere and it works just fine, except that I normally have to do this:

$ds = lib_open_dataset($some_sql)
$table = $ds.Tables[0]
foreach ($row in $table.Rows) {
    # etc
}

所以我创建了一个新的简单包装函数来避免取消引用第一个表的额外步骤:

So I created a new simple wrapper function to avoid the extra step of dereferencing the first table:

function lib_open_table([string] $sql) {
    $ds = lib_open_dataset $sql
    return $ds.Tables[0]
}

问题是,出于某种原因,从这里返回的是表的 Rows 集合,而不是 本身.这会导致如上编写的 foreach 行循环失败,并显示无法索引到空数组".例外.经过多次反复试验,我发现这是可行的:

The problem is that what's being returned from here is the Rows collection of the table for some reason, not the table itself. This causes the foreach row loop written as above to fail with a "Cannot index into a null array." exception. After much trial and error I figured out this works:

foreach ($row in $table) {
    # etc
}

注意 $table.Rows$tableforeach 语句中的区别.这有效.因为 $table 实际上指向 Rows 集合.如果声明

Note the difference between $table.Rows and just $table in the foreach statement. This works. Because $table actually points to the Rows collection. If the statement

return $ds.Tables[0]

应该是正确的,为什么函数返回表对象的子集合而不是表本身?

is supposedly correct, why is the function returning a child collection of the table object instead of the table itself?

我猜想 Powershell 函数的工作方式显然导致了这种情况,但我不知道是什么原因.

I'm guessing there's something in the way Powershell functions work that's causing this obviously, but I can't figure out what.

推荐答案

您可以使用逗号运算符将行集合包装在一个数组中,以便在展开数组时您会得到原始的行集合,例如:

You can use the comma operator to wrap the rows collection in an array so that when the array is unrolled you wind up with the original rows collection e.g.:

function lib_open_table([string] $sql) {
    $ds = lib_open_dataset $sql    
    return ,$ds.Tables[0]
}

本质上,您无法阻止 PowerShell 展开数组/集合.您能做的最好的事情是通过将数组/集合包装在另一个单元素数组中来解决该行为.

Essentially you can't prevent PowerShell from unrolling arrays/collections. The best you can do is workaround that behavior by wrapping the array/collection within another, single element array.

这篇关于PowerShell 函数中返回 DataSet/DataTable 的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆