Home > database >  PowerShell DataTable delete column containing value "description"
PowerShell DataTable delete column containing value "description"

Time:08-11

I would like to delete all empty rows from the DataTable below as well as delete the column containing the value "description". I am able to delete all empty rows; however, I can't figure out how to also explicitly delete description from the DataTable.

Original DataTable:

dev_id              : 4721
office_id           : 355
name                : Bobby
ip                  : 10.10.10.1
ipv6                : 2001:1930:ff28:ff00::1
mac                 :
serial_num          : XX234555
platform            : Supercode
                    :
description         : I;need;to;delete;this;
                    :  
                    : 
max_speed           : 100000

Code:

$myreader = $mycommand.ExecuteReader()
$DevicesDataTable.Load($myreader)
$myconnection.Close()

$Columns = $DevicesDataTable.Columns.Count
$Rows    = $DevicesDataTable.Rows.Count

for ($r = 0; $r -lt $Rows; $r  ) {    
    $Empty = 0
    for ($c = 0; $c -lt $Columns; $c  ) {

        if (($DevicesDataTable.Rows[$r].IsNull($c)) -or ($DevicesDataTable.Rows[$r].Equals("description"))) {
            $Empty  
        }
    }
    if ($Empty -eq $Columns) {
        $DevicesDataTable.Rows[$r].Delete()
    }
}
# Delete
$DevicesDataTable.AcceptChanges()

Write-Output $DevicesDataTable

Result:
Note DataTable below still shows description:

dev_id              : 4721
office_id           : 355
name                : Bobby
ip                  : 10.10.10.1
ipv6                : 2001:1930:ff28:ff00::1
serial_num          : XX234555
platform            : Supercode
description         : I;need;to;delete;this;
max_speed           : 100000

Note: I am able to identify the column containing "description", however, I'm not sure how to delete the respective row via the correct method:

if ($DevicesDataTable.Columns[$c].ColumnName.Equals("description"))

CodePudding user response:

You can drop a column from the data table by calling Remove() on the Columns collection:

$DevicesDataTable.Columns.Remove('description')
  • Related