'How do I add a new column to an existing DataTable and fill it with a default value?
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?
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mathias R. Jessen |
