DataTable.Rows.Find(MultiplePrimaryKey)在Powershell中

时间:2018-06-06 18:06:57

标签: c# .net vb.net powershell datatable

我正在使用SQL Server表,我将作为数据表进行修改并将数据保存回数据库。

我现在卡在寻找DataTable.Rows.Find(PrimaryKey)的正确语法

为简单起见,我创建了一个包含一些数据的简单数据表 您也可以在最后测试它。

这是我的语法。

[System.Data.DataTable]$dtGL = New-Object System.Data.DataTable("GL")
#Schemas
$dtGL.Columns.Add("Account", "String") | Out-Null
$dtGL.Columns.Add("Property", "String") | Out-Null
$dtGL.Columns.Add("Date", "DateTime") | Out-Null
$dtGL.Columns.Add("Amount", "Decimal") | Out-Null

[System.Data.DataColumn[]]$KeyColumn = ($dtGL.Columns["Account"],$dtGL.Columns["Property"],$dtGL.Columns["Date"])
$dtGL.PrimaryKey = $KeyColumn 

#Records
$dtGL.Rows.Add('00001','1000','1/1/2018','185') | Out-Null 
$dtGL.Rows.Add('00001','1000','1/2/2018','486') | Out-Null
$dtGL.Rows.Add('00001','1001','1/1/2018','694') | Out-Null
$dtGL.Rows.Add('00001', '1001', '1/2/2018', '259') | Out-Null

[String[]]$KeyToFind = '00001', '1001', '01/01/2018'
$FoundRows = $dtGL.Rows.Find($KeyToFind)
$FoundRows | Out-GridView 

我收到以下错误

Exception calling "Find" with "1" argument(s): "Expecting 3 value(s) for the key being indexed, but received 1 value(s)."
At C:\Users\MyUserName\OneDrive - MyUserName\MyCompany\PowerShell\Samples\Working With DataTable.ps1:32 char:5
+     $FoundRows = $dtGL.Rows.Find($KeyToFind)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

我也尝试将参数分开

$P01 = '00001'
$P02 = '1001'
$P03 = '01/01/2018'

$FoundRows = $dtGL.Rows.Find($P01,$P02,$P03)

这是错误

Cannot find an overload for "Find" and the argument count: "3".
+     $FoundRows = $dtGL.Rows.Find($P01,$P02,$P03)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

2 个答案:

答案 0 :(得分:4)

DataRowCollection.Find需要一个对象数组。在编辑之前,您显示您传入了一系列字符串。如果每个主键列都是String类型,这将起作用。由于你有一个DateTime,你需要传递一个Object数组,Date列的值应该是DateTime类型。

尝试将KeyToFind的实现方式更改为对象数组,并沿途投射每种不同的类型:

[Object[]]$KeyToFind = [String]'00001', [String]'1001', [DateTime]'01/01/2018'

答案 1 :(得分:1)

这应该运作良好,我尝试如下:

$P01 = '00001'
$P02 = '1001'
$P03 = '01/01/2018'

$FoundRows = $dtGL.Rows.Find(@($P01,$P02,$P03))
相关问题