-
Notifications
You must be signed in to change notification settings - Fork 14
/
ConvertTo-DataTable.ps1
90 lines (72 loc) · 5.8 KB
/
ConvertTo-DataTable.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
function ConvertTo-DataTable
{
<#
.Synopsis
Creates a DataTable from an object
.Description
Creates a DataTable from an object, containing all properties (except built-in properties from a database)
.Example
Get-ChildItem| Select Name, LastWriteTime | ConvertTo-DataTable
.Link
Select-DataTable
.Link
Import-DataTable
.Link
Export-Datatable
#>
[OutputType([Data.DataTable])]
param(
# The input objects
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)]
[PSObject[]]
$InputObject
)
begin {
$outputDataTable = new-object Data.datatable
$knownColumns = @{}
}
process {
foreach ($In in $InputObject) {
$DataRow = $outputDataTable.NewRow()
$isDataRow = $in.psobject.TypeNames -like "*.DataRow*" -as [bool]
$simpleTypes = ('System.Boolean', 'System.Byte[]', 'System.Byte', 'System.Char', 'System.Datetime', 'System.Decimal', 'System.Double', 'System.Guid', 'System.Int16', 'System.Int32', 'System.Int64', 'System.Single', 'System.UInt16', 'System.UInt32', 'System.UInt64')
$SimpletypeLookup = @{}
foreach ($s in $simpleTypes) {
$SimpletypeLookup[$s] = $s
}
foreach($property in $In.PsObject.properties) {
if ($isDataRow -and
'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors' -contains $property.Name) {
continue
}
$propName = $property.Name
$propValue = $property.Value
$IsSimpleType = $SimpletypeLookup.ContainsKey($property.TypeNameOfValue)
if (-not $outputDataTable.Columns.Contains($propName)) {
$outputDataTable.Columns.Add((
New-Object Data.DataColumn -Property @{
ColumnName = $propName
DataType = if ($issimpleType) {
$property.TypeNameOfValue
} else {
'System.Object'
}
}
))
}
$DataRow.Item($propName) = if ($isSimpleType -and $propValue) {
$propValue
} elseif ($propValue) {
[PSObject]$propValue
} else {
[DBNull]::Value
}
}
$outputDataTable.Rows.Add($DataRow)
}
}
end
{
,$outputDataTable
}
}