Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Last active February 6, 2023 19:01
Show Gist options
  • Save JustinGrote/8afdbb8611c117327fad719f54156abf to your computer and use it in GitHub Desktop.
Save JustinGrote/8afdbb8611c117327fad719f54156abf to your computer and use it in GitHub Desktop.
Build a DataTable from an Array in Powershell. All objects should have the same properties as the first object.
using namespace System.Data
function ConvertTo-DataTable {
<#
.SYNOPSIS
Takes an array and converts it to a datatable, useful for sql or bulk transactions. All objects must be the same (or at least share properties with the first object)
.EXAMPLE
convertto-datatable @(
[PSCustomObject]@{Name = 'Test'; Food = 'Burgers' },
[PSCustomObject]@{Name = 'Test2'; Food = 'Fries' },
[PSCustomObject]@{Name = 'Test3'; Food = 'Coke' },
[PSCustomObject]@{Name = 'Test4'; Food = 'Sandwich' }
)
#>
[CmdletBinding()]
param([Object[]]$array)
#Makes a new table named mytable
[DataTable]$dataTable = 'MyTable'
#We are assuming all items are the same.
foreach ($column in $array[0].psobject.properties.name) {
[void]$dataTable.Columns.Add($column)
}
[string[]]$columns = $dataTable.columns.columnName
$i = 1
$total = $array.count
foreach ($item in $array) {
Write-Debug "Processing Item $i of $total"
$row = $dataTable.NewRow()
foreach ($property in $columns) {
$row.$property = $item.$property
}
[void]$dataTable.Rows.Add($row)
$i++
}
return $dataTable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment