-
Notifications
You must be signed in to change notification settings - Fork 14
/
Export-DataTable.ps1
77 lines (65 loc) · 4.98 KB
/
Export-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
function Export-DataTable
{
<#
.Synopsis
Exports objects to a datatable on disk
.Description
Exports objects to a datatable. Objects in the datatable must be serialiazble in order to be stored.
.Link
Import-DataTable
.Link
ConvertTo-DataTable
.Notes
A datatable will not be able to be exported if it contains live objects that do not implement ISerializable.
.Example
dir |
select Name, LastWriteTime, CreationTime |
Export-DataTable -OutputPath .\Files.bin
Import-DataTable .\Files.bin
#>
[CmdletBinding(DefaultParameterSetName='InputObject')]
[OutputType([Nullable])]
param(
# The input object
[Parameter(Mandatory=$true,ParameterSetName='InputObject', ValueFromPipeline=$true)]
[PSObject[]]
$InputObject,
# An existing data table. Use this parameter to store data tables created with New-DataTable
[Parameter(Mandatory=$true,ParameterSetName='ExistingDataTable')]
[Data.Datatable]
$DataTable,
# The output path
[Parameter(Mandatory=$true,Position=0)]
[string]
$OutputPath
)
begin {
# Create a collection to hold all objects
$allObjects = New-Object Collections.ArrayList
}
process {
#region Accumulate Input
if ($PSCmdlet.ParameterSetName -eq 'InputObject') {
$null = $allObjects.AddRange($InputObject)
}
#endregion Accumulate Input
}
end {
# If input was supplied by the pipeline, convert it to a data table
if ($allObjects.Count) {
$DataTable = ConvertTo-DataTable -InputObject $allObjects
}
# Determine the absolute path of the output file
$outFile = "$($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath))"
# Open the file stream
$fileStream = New-Object IO.FileStream $outFile, "OpenOrCreate"
# Open a GZip stream on the file stream
$cs = New-Object System.IO.Compression.GZipStream ($fileStream, [Io.Compression.CompressionMode]"Compress")
# Serialize and save the data
(New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter).Serialize($cs, $DataTable)
# Close the compressed stream
$cs.Close()
# close the file stream
$fileStream.Close()
}
}