I have written previously about how to convert an object to a DataTable and how to create one based on an existing MSSQL table, but now I will share a function to create a new empty DataTable. Sure, this isn’t very complicated to do manually, but using this function you can define the table structure using an ordered dictionary, which makes it much easier to update later if needed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function New-DataTable { | |
<# | |
.SYNOPSIS | |
Create a new DataTable. | |
.DESCRIPTION | |
Create a new DataTable. | |
.EXAMPLE | |
` | |
$myColumns = [ordered] @{ | |
ID = [int32] | |
Name = [string] | |
Age = [int] | |
Date = [DateTime] | |
} | |
$myTable = New-DataTable -TableName 'MyTable' -Columns $myColumns | |
.NOTES | |
Author: Øyvind Kallstad | |
Date: 20.10.2014 | |
Version: 1.0 | |
#> | |
[CmdletBinding()] | |
[OutputType([System.Data.DataTable])] | |
param ( | |
[parameter()] | |
[string] $TableName, | |
# Use an ordered dictionary to define the table columns. | |
[parameter()] | |
[System.Collections.Specialized.OrderedDictionary] $Columns | |
) | |
# create new datatable | |
$newDataTable = New-Object –TypeName 'System.Data.DataTable' –ArgumentList $TableName | |
Write-Verbose "DataTable created '$TableName'" | |
# create columns | |
if ($PSBoundParameters['Columns']) { | |
$Columns.GetEnumerator() | ForEach-Object { | |
$columnName = $_.Key | |
$columnType = $_.Value.ToString() | |
$dataColumn = New-Object –TypeName 'System.Data.DataColumn' –ArgumentList ($columnName,$columnType) | |
$newDataTable.Columns.Add($dataColumn) | |
Write-Verbose "New column created '$columnName'" | |
} | |
} | |
Write-Output @(,$newDataTable) | |
} |