Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading