Home > Mobile >  How do I add a new column to an existing DataTable and fill it with a default value?
How do I add a new column to an existing DataTable and fill it with a default value?

Time:03-10

Suppose I have a Datatable in Powershell that looks like this:

ID    Value
-----------
1     Foo
2     Bar

And I wanted to add a Status column with the default value of "Normal". I create the new column with:

$MyDataTable.Columns.Add("Status", [String]) | Out-Null
$MyDataTable.Columns["Status"].DefaultValue = "Normal"

$MyDataTable | Format-Table

The new column is created but the default value is not applied.

ID    Value    Status
---------------------
1     Foo
2     Bar

Given it is an existing DataTable, how do I fill the new column with its default value?

CodePudding user response:

Set the DefaultValue on the column before adding it to the table:

# Define column with default value
$StatusColumn = [System.Data.DataColumn]::new('Status', [string])
$StatusColumn.DefaultValue = 'Normal'

# Add column definition to table
$MyDataTable.Columns.Add($StatusColumn)
  • Related