I am trying to remove a handful of rows from a .NET DataTable using Powershell, based on a list that I have. Here is my condensed code:
Here is my datatable declaration:
$Global:dt = New-Object System.Data.Datatable
$dt.Columns.Add("Name")
$dt.Columns.Add("AccountID")
I know I am populating my datatable correctly. Here is my code where I try and conditionally delete something:
$testname = "John Smith"
foreach ($id in $DeleteIDs)
{
$dt.Select("Name = '" + $testname + "' AND AccountId = '" + $id + "'").Delete()
}
I may be crazy but I sware this worked for me the first time I tried it. But now I am receiving the following error:
Method invocation failed because [System.Data.DataRow[]] doesn't contain a method named 'Delete'.
At P:\My Documents\Scripts\myLoc\myScript.ps1:152 char:9
+ $dt.Select("Name= '" + $testname+ "' AND AccountId = '" + $id + "' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
This says System.Data.DataRow does not contain a Delete method. I know this isn't try. When I place a breakpoint and run a $dt | gm I get the following.
PS C:\WINDOWS\system32>> $dt | gm
TypeName: System.Data.DataRow
System.Data.DataRow[]doesn't contain a delete method, subtle but important difference - you're dealing with an array ofDataRows at this point. You need to iterate the collection to get access to the delete method of each object.