-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge-Csv.ps1
103 lines (93 loc) · 3.17 KB
/
Merge-Csv.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
91
92
93
94
95
96
97
98
99
100
101
102
103
using namespace System.Text
using namespace System.IO
using namespace System.Management.Automation
function Merge-Csv {
[cmdletbinding()]
param(
[Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[alias('FullName')]
[string[]] $Path,
[Parameter(Mandatory)]
[string] $DestinationPath,
[Parameter()]
[EncodingTransformation()]
[ArgumentCompleter([EncodingCompleter])]
[Encoding] $Encoding = 'utf8',
[Parameter()]
[switch] $PassThru,
[Parameter()]
[switch] $Force
)
begin {
$isFirstObject = $true
$Destination = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath)
}
process {
foreach($chunk in $Path) {
try {
$reader = [StreamReader]::new($chunk, $Encoding, $true)
$headers = $reader.ReadLine()
if($isFirstObject) {
$params = @{
Path = $Destination
ItemType = 'File'
Force = $Force.IsPresent
ErrorAction = 'Stop'
}
$Destination = New-Item @params
$isFirstObject = $false
$writer = [StreamWriter]::new($Destination, $Encoding)
$writer.WriteLine($headers)
}
while(-not $reader.EndOfStream) {
$writer.WriteLine($reader.ReadLine())
}
}
catch [DirectoryNotFoundException] {
$PSCmdlet.ThrowTerminatingError(
[ErrorRecord]::new(
[DirectoryNotFoundException]::new(
$_.Exception.Message +
' Use the -Force parameter to create new folders.'
),
'DirectoryNotFound',
[ErrorCategory]::WriteError,
$DestinationPath
)
)
}
catch [IOException] {
if($_.Exception.Message.EndsWith('already exists.')) {
$PSCmdlet.ThrowTerminatingError(
[ErrorRecord]::new(
[IOException]::new(
$_.Exception.Message +
' Use the -Force parameter to overwrite the file.'
),
'FileExists',
[ErrorCategory]::WriteError,
$DestinationPath
)
)
}
$PSCmdlet.ThrowTerminatingError($_)
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
finally {
if($reader) {
$reader.Dispose()
}
}
}
}
end {
if($writer) {
$writer.Dispose()
}
if($PassThru.IsPresent) {
$Destination
}
}
}