forked from ktaranov/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CsvSqlimport.ps1
1272 lines (1064 loc) · 51.6 KB
/
CsvSqlimport.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Function Import-CsvToSql {
<#
.SYNOPSIS
Efficiently imports very large (and small) CSV files into SQL Server using only the .NET Framework and PowerShell.
.DESCRIPTION
Import-CsvToSql takes advantage of .NET's super fast SqlBulkCopy class to import CSV files into SQL Server at up to 90,000
rows a second.
The entire import is contained within a transaction, so if a failure occurs or the script is aborted, no changes will persist.
If the table specified does not exist, it will be automatically created using best guessed data types. In addition,
the destination table can be truncated prior to import.
The Query parameter be used to import only data returned from a SQL Query executed against the CSV file(s). This function
supports a number of bulk copy options. Please see parameter list for details.
THIS CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
.PARAMETER CSV
Required. The location of the CSV file(s) to be imported. Multiple files are allowed, so long as they are formatted
similarly. If no CSV file is specified, a Dialog box will appear.
.PARAMETER FirstRowColumns
Optional. This parameter specifies whether the first row contains column names. If the first row does not contain column
names and -Query is specified, use field names "column1, column2, column3" and so on.
.PARAMETER Delimiter
Optional. If you do not pass a Delimiter, then a comma will be used. Valid Delimiters include: tab "`t", pipe "|",
semicolon ";", and space " ".
.PARAMETER SqlServer
Required. The destination SQL Server.
.PARAMETER SqlCredential
Connect to SQL Server using specified SQL Login credentials.
.PARAMETER Database
Required. The name of the database where the CSV will be imported into. This parameter is autopopulated using the
-SqlServer and -SqlCredential (optional) parameters.
.PARAMETER Table
SQL table or view where CSV will be imported into.
If a table name is not specified, the table name will be automatically determined from filename, and a prompt will appear
to confirm table name.
If table does not currently exist, it will created. SQL datatypes are determined from the first row of the CSV that
contains data (skips first row if -FirstRowColumns). Datatypes used are: bigint, numeric, datetime and varchar(MAX).
If the automatically generated table datatypes do not work for you, please create the table prior to import.
.PARAMETER Truncate
Truncate table prior to import.
.PARAMETER Safe
Optional. By default, Import-CsvToSql uses StreamReader for imports. StreamReader is super fast, but may not properly parse some files.
Safe uses OleDb to import the records, it's slower, but more predictable when it comes to parsing CSV files. A schema.ini is automatically
generated for best results. If schema.ini currently exists in the directory, it will be moved to a temporary location, then moved back.
OleDB also enables the script to use the -Query parameter, which enables you to import specific subsets of data within a CSV file. OleDB
imports at up to 21,000 rows/sec.
.PARAMETER Turbo
Optional. Cannot be used in conjunction with -Query.
Remember the Turbo button? This one actually works. Turbo is mega fast, but may not handle some datatypes as well as other methods.
If your CSV file is rather vanilla and doesn't have a ton of NULLs, Turbo may work well for you. Note: Turbo mode uses a Table Lock.
StreamReader/Turbo imports at up to 90,000 rows/sec (well, 93,000 locally for a 19 column file so, really, the number may be over
100,000 rows/sec for tables with only a couple columns using optimized datatypes).
.PARAMETER First
Only import first X rows. Count starts at the top of the file, but skips the first row if FirstRowColumns was specifeid.
Use -Query if you need advanced First (TOP) functionality.
.PARAMETER Query
Optional. Cannot be used in conjunction with -Turbo or -First. When Query is specified, the slower import method, OleDb,
will be used.
If you want to import just the results of a specific query from your CSV file, use this parameter.
To make command line queries easy, this module will convert the word "csv" to the actual CSV formatted table name.
If the FirstRowColumns switch is not used, the query should use column1, column2, column3, etc
Example: select column1, column2, column3 from csv where column2 > 5
Example: select distinct artist from csv
Example: select top 100 artist, album from csv where category = 'Folk'
See EXAMPLES for more example syntax.
.PARAMETER TableLock
SqlBulkCopy option. Per Microsoft "Obtain a bulk update lock for the duration of the bulk copy operation. When not
specified, row locks are used." TableLock is automatically used when Turbo is specified.
.PARAMETER CheckConstraints
SqlBulkCopy option. Per Microsoft "Check constraints while data is being inserted. By default, constraints are not checked."
.PARAMETER FireTriggers
SqlBulkCopy option. Per Microsoft "When specified, cause the server to fire the insert triggers for the rows being inserted
into the database."
.PARAMETER KeepIdentity
SqlBulkCopy option. Per Microsoft "Preserve source identity values. When not specified, identity values are assigned by
the destination."
.PARAMETER KeepNulls
SqlBulkCopy option. Per Microsoft "Preserve null values in the destination table regardless of the settings for default
values. When not specified, null values are replaced by default values where applicable."
.PARAMETER shellswitch
Internal parameter.
.PARAMETER SqlCredentialPath
Internal parameter.
.NOTES
Author: Chrissy LeMaire (@cl), netnerds.net
.LINK
https://blog.netnerds.net/2015/09/import-csvtosql-super-fast-csv-to-sql-server-import-powershell-module/
.EXAMPLE
Import-CsvToSql -Csv C:\temp\housing.csv -SqlServer sql001 -Database markets
Imports the entire *comma delimited* housing.csv to the SQL "markets" database on a SQL Server named sql001.
Since a table name was not specified, the table name is automatically determined from filename as "housing"
and a prompt will appear to confirm table name.
The first row is not skipped, as it does not contain column names.
.EXAMPLE
Import-CsvToSql -Csv .\housing.csv -SqlServer sql001 -Database markets -Table housing -First 100000 -Safe -Delimiter "`t" -FirstRowColumns
Imports the first 100,000 rows of the tab delimited housing.csv file to the "housing" table in the "markets" database on a SQL Server
named sql001. Since Safe was specified, the OleDB method will be used for the bulk import. It's assumed Safe was used because
the first attempt without -Safe resulted in an import error. The first row is skipped, as it contains column names.
.EXAMPLE
Import-CsvToSql -csv C:\temp\huge.txt -sqlserver sqlcluster -Database locations -Table latitudes -Delimiter "|" -Turbo
Imports all records from the pipe delimited huge.txt file using the fastest method possible into the latitudes table within the
locations database. Obtains a table lock for the duration of the bulk copy operation. This specific command has been used
to import over 10.5 million rows in 2 minutes.
.EXAMPLE
Import-CsvToSql -Csv C:\temp\housing.csv, .\housing2.csv -SqlServer sql001 -Database markets -Table `
housing -Delimiter "`t" -query "select top 100000 column1, column3 from csv" -Truncate
Truncates the "housing" table, then imports columns 1 and 3 of the first 100000 rows of the tab-delimited
housing.csv in the C:\temp directory, and housing2.csv in the current directory. Since the query is executed against
both files, a total of 200,000 rows will be imported.
.EXAMPLE
Import-CsvToSql -Csv C:\temp\housing.csv -SqlServer sql001 -Database markets -Table housing -query `
"select address, zip from csv where state = 'Louisiana'" -FirstRowColumns -Truncate -FireTriggers
Uses the first line to determine CSV column names. Truncates the "housing" table on the SQL Server,
then imports the address and zip columns from all records in the housing.csv where the state equals Louisiana.
Triggers are fired for all rows. Note that this does slightly slow down the import.
.NOTES
Author: Chrissy LeMaire
Original Link: https://github.com/ctrlbold/dbatools/blob/master/Functions/CsvSqlimport.ps1
Created Date: 2015-09-01
#>
[CmdletBinding(DefaultParameterSetName="Default")]
Param(
[string[]]$Csv,
[Parameter(Mandatory=$true)]
[string]$SqlServer,
[object]$SqlCredential,
[string]$Table,
[switch]$Truncate,
[string]$Delimiter = ",",
[switch]$FirstRowColumns,
[parameter(ParameterSetName="reader")]
[switch]$Turbo,
[parameter(ParameterSetName="ole")]
[switch]$Safe,
[int]$First = 0,
[parameter(ParameterSetName="ole")]
[string]$Query = "select * from csv",
[int]$BatchSize = 50000,
[int]$NotifyAfter,
[switch]$TableLock,
[switch]$CheckConstraints,
[switch]$FireTriggers,
[switch]$KeepIdentity,
[switch]$KeepNulls,
[switch]$shellswitch,
[string]$SqlCredentialPath
)
DynamicParam {
if ($sqlserver.length -gt 0) {
# Auto populate database list from specified sqlserver
$paramconn = New-Object System.Data.SqlClient.SqlConnection
if ($SqlCredentialPath.length -gt 0) {
$SqlCredential = Import-CliXml $SqlCredentialPath
}
if ($SqlCredential.count -eq 0 -or $SqlCredential -eq $null) {
$paramconn.ConnectionString = "Data Source=$sqlserver;Integrated Security=True;"
} else {
$paramconn.ConnectionString = "Data Source=$sqlserver;User Id=$($SqlCredential.UserName); Password=$($SqlCredential.GetNetworkCredential().Password);"
}
try {
$paramconn.Open()
$sql = "select name from master.dbo.sysdatabases"
$paramcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $paramconn, $null)
$paramdt = New-Object System.Data.DataTable
$paramdt.Load($paramcmd.ExecuteReader())
$databaselist = $paramdt.rows.name
$null = $paramcmd.Dispose()
$null = $paramconn.Close()
$null = $paramconn.Dispose()
} catch {
# But if the routine fails, at least let them specify a database manually
$databaselist = ""
}
# Reusable parameter setup
$newparams = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.Mandatory = $false
# Database list parameter setup
$dbattributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$dbattributes.Add($attributes)
# If a list of databases were returned, populate the parameter set
if ($databaselist.length -gt 0) {
$dbvalidationset = New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList $databaselist
$dbattributes.Add($dbvalidationset)
}
$Database = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Database", [String], $dbattributes)
$newparams.Add("Database", $Database)
return $newparams
}
}
Begin {
Function Parse-OleQuery {
<#
.SYNOPSIS
Tests to ensure query is valid. This will be used for the GUI.
.EXAMPLE
Parse-OleQuery -Csv sqlservera -Query $query -FirstRowColumns $FirstRowColumns -delimiter $delimiter
.OUTPUT
#>
param(
[string]$Provider,
[Parameter(Mandatory=$true)]
[string[]]$csv,
[Parameter(Mandatory=$true)]
[string]$Query,
[Parameter(Mandatory=$true)]
[bool]$FirstRowColumns,
[Parameter(Mandatory=$true)]
[string]$delimiter
)
if ($query.ToLower() -notmatch "\bcsv\b") {
return "SQL statement must contain the word 'csv'."
}
try {
$datasource = Split-Path $csv[0]
$tablename = (Split-Path $csv[0] -leaf).Replace(".","#")
switch ($FirstRowColumns) {
$true { $FirstRowColumns = "Yes" }
$false { $FirstRowColumns = "No" }
}
if ($provider -ne $null) {
$connstring = "Provider=$provider;Data Source=$datasource;Extended Properties='text';"
} else {
$connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$datasource;Extended Properties='text';"
}
$conn = New-Object System.Data.OleDb.OleDbconnection $connstring
$conn.Open()
$sql = $Query -replace "\bcsv\b"," [$tablename]"
$cmd = New-Object System.Data.OleDB.OleDBCommand
$cmd.Connection = $conn
$cmd.CommandText = $sql
$null = $cmd.ExecuteReader()
$cmd.Dispose()
$conn.Dispose()
return $true
} catch { return $false }
}
Function Test-SqlConnection {
<#
.SYNOPSIS
Uses System.Data.SqlClient to gather list of user databases.
.EXAMPLE
$SqlCredential = Get-Credential
Get-SqlDatabases -SqlServer sqlservera -SqlCredential $SqlCredential
.OUTPUT
Array of user databases
#>
param(
[Parameter(Mandatory=$true)]
[string]$SqlServer,
[object]$SqlCredential
)
$testconn = New-Object System.Data.SqlClient.SqlConnection
if ($SqlCredential.count -eq 0) {
$testconn.ConnectionString = "Data Source=$sqlserver;Integrated Security=True;Connection Timeout=3"
} else {
$testconn.ConnectionString = "Data Source=$sqlserver;User Id=$($SqlCredential.UserName); Password=$($SqlCredential.GetNetworkCredential().Password);Connection Timeout=3"
}
try {
$testconn.Open()
$testconn.Close()
$testconn.Dispose()
return $true
} catch {
$message = $_.Exception.Message.ToString()
Write-Verbose $message
if ($message -match "A network") { $message = "Can't connect to $sqlserver." }
elseif ($message -match "Login failed for user") { $message = "Login failed for $username." }
return $message
}
}
Function Get-SqlDatabases {
<#
.SYNOPSIS
Uses System.Data.SqlClient to gather list of user databases.
.EXAMPLE
$SqlCredential = Get-Credential
Get-SqlDatabases -SqlServer sqlservera -SqlCredential $SqlCredential
.OUTPUT
Array of user databases
#>
param(
[Parameter(Mandatory=$true)]
[string]$SqlServer,
[object]$SqlCredential
)
$paramconn = New-Object System.Data.SqlClient.SqlConnection
if ($SqlCredential.count -eq 0) {
$paramconn.ConnectionString = "Data Source=$sqlserver;Integrated Security=True;Connection Timeout=3"
} else {
$paramconn.ConnectionString = "Data Source=$sqlserver;User Id=$($SqlCredential.UserName); Password=$($SqlCredential.GetNetworkCredential().Password);Connection Timeout=3"
}
try {
$paramconn.Open()
$sql = "select name from master.dbo.sysdatabases where dbid > 4 order by name"
$paramcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $paramconn, $null)
$datatable = New-Object System.Data.DataTable
[void]$datatable.Load($paramcmd.ExecuteReader())
$databaselist = $datatable.rows.name
$null = $paramcmd.Dispose()
$null = $paramconn.Close()
$null = $paramconn.Dispose()
return $databaselist
} catch { throw "Cannot access $sqlserver" }
}
Function Get-SqlTables {
<#
.SYNOPSIS
Uses System.Data.SqlClient to gather list of user databases.
.EXAMPLE
$SqlCredential = Get-Credential
Get-SqlTables -SqlServer sqlservera -Database mydb -SqlCredential $SqlCredential
.OUTPUT
Array of tables
#>
param(
[Parameter(Mandatory=$true)]
[string]$SqlServer,
[string]$Database,
[object]$SqlCredential
)
$tableconn = New-Object System.Data.SqlClient.SqlConnection
if ($SqlCredential.count -eq 0) {
$tableconn.ConnectionString = "Data Source=$sqlserver;Integrated Security=True;Connection Timeout=3"
} else {
$username = ($SqlCredential.UserName).TrimStart("\")
$tableconn.ConnectionString = "Data Source=$sqlserver;User Id=$username; Password=$($SqlCredential.GetNetworkCredential().Password);Connection Timeout=3"
}
try {
$tableconn.Open()
$sql = "select name from $database.sys.tables order by name"
$tablecmd = New-Object System.Data.SqlClient.SqlCommand($sql, $tableconn, $null)
$datatable = New-Object System.Data.DataTable
[void]$datatable.Load($tablecmd.ExecuteReader())
$tablelist = $datatable.rows.name
$null = $tablecmd.Dispose()
$null = $tableconn.Close()
$null = $tableconn.Dispose()
return $tablelist
} catch { return }
}
Function Get-Columns {
<#
.SYNOPSIS
TextFieldParser will be used instead of an OleDbConnection.
This is because the OleDbConnection driver may not exist on x64.
.EXAMPLE
$columns = Get-Columns -Csv .\myfile.csv -Delimiter "," -FirstRowColumns $true
.OUTPUT
Array of column names
#>
param(
[Parameter(Mandatory=$true)]
[string[]]$Csv,
[Parameter(Mandatory=$true)]
[string]$Delimiter,
[Parameter(Mandatory=$true)]
[bool]$FirstRowColumns
)
$columnparser = New-Object Microsoft.VisualBasic.FileIO.TextFieldParser($csv[0])
$columnparser.TextFieldType = "Delimited"
$columnparser.SetDelimiters($Delimiter)
$rawcolumns = $columnparser.ReadFields()
if ($FirstRowColumns -eq $true) {
$columns = ($rawcolumns | ForEach-Object { $_ -Replace '"' } | Select-Object -Property @{Name="name"; Expression = {"[$_]"}}).name
} else {
$columns = @()
foreach ($number in 1..$rawcolumns.count ) { $columns += "[column$number]" }
}
$columnparser.Close()
$columnparser.Dispose()
return $columns
}
Function Get-ColumnText {
<#
.SYNOPSIS
Returns an array of data, which can later be parsed for potential datatypes.
.EXAMPLE
$columns = Get-Columns -Csv .\myfile.csv -Delimiter ","
.OUTPUT
Array of column data
#>
param(
[Parameter(Mandatory=$true)]
[string[]]$Csv,
[Parameter(Mandatory=$true)]
[string]$Delimiter
)
$columnparser = New-Object Microsoft.VisualBasic.FileIO.TextFieldParser($csv[0])
$columnparser.TextFieldType = "Delimited"
$columnparser.SetDelimiters($Delimiter)
$line = $columnparser.ReadLine()
# Skip a line, in case first line are column names
$line = $columnparser.ReadLine()
$datatext = $columnparser.ReadFields()
$columnparser.Close()
$columnparser.Dispose()
return $datatext
}
Function Write-Schemaini {
<#
.SYNOPSIS
Unfortunately, passing delimiter within the OleDBConnection connection string is unreliable, so we'll use schema.ini instead
The default delimiter in Windows changes depending on country, so we'll do this for every delimiter, even commas.
Get OLE datatypes based on best guess of column data within the -Columns parameter.
Sometimes SQL will accept a datetime that OLE won't, so Text will be used for datetime.
.EXAMPLE
$columns = Get-Columns -Csv C:\temp\myfile.csv -Delimiter ","
$movedschemainis = Write-Schemaini -Csv C:\temp\myfile.csv -Columns $columns -ColumnText $columntext -Delimiter "," -FirstRowColumns $true
.OUTPUT
Creates new schema files, that look something like this:
[housingdata.csv]
Format=Delimited(,)
ColNameHeader=True
Col1="House ID" Long
Col2="Description" Memo
Col3="Price" Double
Returns an array of existing schema files that have been moved, if any.
#>
param(
[Parameter(Mandatory=$true)]
[string[]]$Csv,
[Parameter(Mandatory=$true)]
[string[]]$Columns,
[string[]]$ColumnText,
[Parameter(Mandatory=$true)]
[string]$Delimiter,
[Parameter(Mandatory=$true)]
[bool]$FirstRowColumns
)
$movedschemainis = @{}
foreach ($file in $csv) {
$directory = Split-Path $file
$schemaexists = Test-Path "$directory\schema.ini"
if ($schemaexists -eq $true) {
$newschemaname = "$env:TEMP\$(Split-Path $file -leaf)-schema.ini"
$movedschemainis.Add($newschemaname,"$directory\schema.ini")
Move-Item "$directory\schema.ini" $newschemaname -Force
}
$filename = Split-Path $file -leaf; $directory = Split-Path $file
Add-Content -Path "$directory\schema.ini" -Value "[$filename]"
Add-Content -Path "$directory\schema.ini" -Value "Format=Delimited($Delimiter)"
Add-Content -Path "$directory\schema.ini" -Value "ColNameHeader=$FirstRowColumns"
$index = 0
$olecolumns = ($columns | ForEach-Object { $_ -Replace "\[|\]", '"' })
foreach ($datatype in $columntext) {
$olecolumnname = $olecolumns[$index]
$index++
try { [System.Guid]::Parse($datatype) | Out-Null; $isguid = $true } catch { $isguid = $false }
if ($isguid -eq $true) { $oledatatype = "Text" }
elseif ([int64]::TryParse($datatype,[ref]0) -eq $true) { $oledatatype = "Long" }
elseif ([double]::TryParse($datatype,[ref]0) -eq $true) { $oledatatype = "Double" }
elseif ([datetime]::TryParse($datatype,[ref]0) -eq $true) { $oledatatype = "Text" }
else { $oledatatype = "Memo" }
Add-Content -Path "$directory\schema.ini" -Value "Col$($index)`=$olecolumnname $oledatatype"
}
}
return $movedschemainis
}
Function New-SqlTable {
<#
.SYNOPSIS
Creates new Table using existing SqlCommand.
SQL datatypes based on best guess of column data within the -ColumnText parameter.
Columns paramter determine column names.
.EXAMPLE
New-SqlTable -Csv $Csv -Delimiter $Delimiter -Columns $columns -ColumnText $columntext -SqlConn $sqlconn -Transaction $transaction
.OUTPUT
Creates new table
#>
param(
[Parameter(Mandatory=$true)]
[string[]]$Csv,
[Parameter(Mandatory=$true)]
[string]$Delimiter,
[string[]]$Columns,
[string[]]$ColumnText,
[System.Data.SqlClient.SqlConnection]$sqlconn,
[System.Data.SqlClient.SqlTransaction]$transaction
)
# Get SQL datatypes by best guess on first data row
$sqldatatypes = @(); $index = 0
foreach ($column in $columntext) {
$sqlcolumnname = $Columns[$index]
$index++
# bigint, float, and datetime are more accurate, but it didn't work
# as often as it should have, so we'll just go for a smaller datatype
if ([int64]::TryParse($column,[ref]0) -eq $true) { $sqldatatype = "varchar(255)" }
elseif ([double]::TryParse($column,[ref]0) -eq $true) { $sqldatatype = "varchar(255)" }
elseif ([datetime]::TryParse($column,[ref]0) -eq $true) { $sqldatatype = "varchar(255)" }
else { $sqldatatype = "varchar(MAX)" }
$sqldatatypes += "$sqlcolumnname $sqldatatype"
}
$sql = "BEGIN CREATE TABLE [$table] ($($sqldatatypes -join ' NULL,')) END"
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
try { $null = $sqlcmd.ExecuteNonQuery()} catch {
$errormessage = $_.Exception.Message.ToString()
throw "Failed to execute $sql. `nDid you specify the proper delimiter? `n$errormessage"
}
Write-Output "[*] Successfully created table $table with the following column definitions:`n $($sqldatatypes -join "`n ")"
# Write-Warning "All columns are created using a best guess, and use their maximum datatype."
Write-Warning "This is inefficient but allows the script to import without issues."
Write-Warning "Consider creating the table first using best practices if the data will be used in production."
}
if ($shellswitch -eq $false) { Write-Output "[*] Started at $(Get-Date)" }
# Load the basics
[void][Reflection.Assembly]::LoadWithPartialName("System.Data")
[void][Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Getting the total rows copied is a challenge. Use SqlBulkCopyExtension.
# http://stackoverflow.com/questions/1188384/sqlbulkcopy-row-count-when-complete
$source = 'namespace System.Data.SqlClient
{
using Reflection;
public static class SqlBulkCopyExtension
{
const String _rowsCopiedFieldName = "_rowsCopied";
static FieldInfo _rowsCopiedField = null;
public static int RowsCopiedCount(this SqlBulkCopy bulkCopy)
{
if (_rowsCopiedField == null) _rowsCopiedField = typeof(SqlBulkCopy).GetField(_rowsCopiedFieldName, BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
return (int)_rowsCopiedField.GetValue(bulkCopy);
}
}
}
'
Add-Type -ReferencedAssemblies 'System.Data.dll' -TypeDefinition $source -ErrorAction SilentlyContinue
}
Process {
# Supafast turbo mode requires a table lock, or it's just regular fast
if ($turbo -eq $true) { $tablelock = $true }
# The query parameter requires OleDB which is invoked by the "safe" variable
# Actually, a select could be performed on the datatable used in StreamReader, too.
# Maybe that will be done later.
if ($query -ne "select * from csv") { $safe = $true }
if ($first -gt 0 -and $query -ne "select * from csv") {
throw "Cannot use both -Query and -First. If a query is necessary, use TOP $first within your SQL statement."
}
# In order to support -First in both Streamreader, and OleDb imports, the query must be modified slightly.
if ($first -gt 0) { $query = "select top $first * from csv" }
# If shell switch occured, and encrypted SQL credentials were written to disk, create $SqlCredential
if ($SqlCredentialPath.length -gt 0) {
$SqlCredential = Import-CliXml $SqlCredentialPath
}
# Get Database string from RuntimeDefinedParameter if required
if ($database -isnot [string]) { $database = $PSBoundParameters.Database }
if ($database.length -eq 0) { throw "You must specify a database." }
# Check to ensure a Windows account wasn't used as a SQL Credential
if ($SqlCredential.count -gt 0 -and $SqlCredential.UserName -like "*\*") { throw "Only SQL Logins can be used as a SqlCredential." }
# If no CSV was specified, prompt the user to select one.
if ($csv.length -eq 0) {
$fd = New-Object System.Windows.Forms.OpenFileDialog
$fd.InitialDirectory = [environment]::GetFolderPath("MyDocuments")
$fd.Filter = "CSV Files (*.csv;*.tsv;*.txt)|*.csv;*.tsv;*.txt"
$fd.Title = "Select one or more CSV files"
$fd.MultiSelect = $true
$null = $fd.showdialog()
$csv = $fd.filenames
if ($csv.length -eq 0) { throw "No CSV file selected." }
} else {
foreach ($file in $csv) {
$exists = Test-Path $file
if ($exists -eq $false) { throw "$file does not exist" }
}
}
# Resolve the full path of each CSV
$resolvedcsv = @()
foreach ($file in $csv) { $resolvedcsv += (Resolve-Path $file).Path }
$csv = $resolvedcsv
# UniqueIdentifier kills OLE DB / SqlBulkCopy imports. Check to see if destination table contains this datatype.
if ($safe -eq $true) {
$sqlcheckconn = New-Object System.Data.SqlClient.SqlConnection
if ($SqlCredential.count -eq 0 -or $SqlCredential -eq $null) {
$sqlcheckconn.ConnectionString = "Data Source=$sqlserver;Integrated Security=True;Connection Timeout=3; Initial Catalog=master"
} else {
$username = ($SqlCredential.UserName).TrimStart("\")
$sqlcheckconn.ConnectionString = "Data Source=$sqlserver;User Id=$username; Password=$($SqlCredential.GetNetworkCredential().Password);Connection Timeout=3; Initial Catalog=master"
}
try { $sqlcheckconn.Open() } catch { throw $_.Exception }
# Ensure database exists
$sql = "select count(*) from master.dbo.sysdatabases where name = '$database'"
$sqlcheckcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlcheckconn)
$dbexists = $sqlcheckcmd.ExecuteScalar()
if ($dbexists -eq $false) { throw "Database does not exist on $sqlserver" }
# Change database after the fact, because if db doesn't exist, the login would fail.
$sqlcheckconn.ChangeDatabase($database)
$sql = "SELECT t.name as datatype FROM sys.columns c
JOIN sys.types t ON t.system_type_id = c.system_type_id
WHERE c.object_id = object_id('$table') and t.name != 'sysname'"
$sqlcheckcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlcheckconn)
$sqlcolumns = New-Object System.Data.DataTable
$sqlcolumns.load($sqlcheckcmd.ExecuteReader("CloseConnection"))
$sqlcheckconn.Dispose()
if ($sqlcolumns.datatype -contains "UniqueIdentifier") {
throw "UniqueIdentifier not supported by OleDB/SqlBulkCopy. Query and Safe cannot be supported."
}
}
if ($safe -eq $true) {
# Check for drivers. First, ACE (Access) if file is smaller than 2GB, then JET
# ACE doesn't handle files larger than 2gb. What gives?
foreach ($file in $csv) {
$filesize = (Get-ChildItem $file).Length / 1GB
if ($filesize -gt 1.99) { $jetonly = $true }
}
if ($jetonly -ne $true) { $provider = (New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.ACE.OLEDB.*" } }
if ($provider -eq $null) {
$provider = (New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.Jet.OLEDB.*" }
}
# If a suitable provider cannot be found (If x64 and Access hasn't been installed)
# switch to x86, because it natively supports JET
if ($provider -ne $null) {
if ($provider -is [system.array]) { $provider = $provider[$provider.GetUpperBound(0)].SOURCES_NAME } else { $provider = $provider.SOURCES_NAME }
}
# If a provider doesn't exist, it is necessary to switch to x86 which natively supports JET.
if ($provider -eq $null) {
# While Install-Module takes care of installing modules to x86 and x64, Import-Module doesn't.
# Because of this, the Module must be exported, written to file, and imported in the x86 shell.
$definition = (Get-Command Import-CsvToSql).Definition
$function = "Function Import-CsvToSql { $definition }"
Set-Content "$env:TEMP\Import-CsvToSql.psm1" $function
# Encode the SQL string, since some characters may mess up after being passed a second time.
$bytes = [System.Text.Encoding]::UTF8.GetBytes($query)
$query = [System.Convert]::ToBase64String($bytes)
# Put switches back into proper format
$switches = @()
$options = "TableLock","CheckConstraints","FireTriggers","KeepIdentity","KeepNulls","Default","Truncate","FirstRowColumns","Safe"
foreach ($option in $options) {
$optionValue = Get-Variable $option -ValueOnly -ErrorAction SilentlyContinue
if ($optionValue -eq $true) { $switches += "-$option" }
}
# Perform the actual switch, which removes any registered Import-CsvToSql modules
# Then imports, and finally re-executes the command.
$csv = $csv -join ","; $switches = $switches -join " "
if ($SqlCredential.count -gt 0) {
$SqlCredentialPath = "$env:TEMP\sqlcredential.xml"
Export-CliXml -InputObject $SqlCredential $SqlCredentialPath
}
$command = "Import-CsvToSql -Csv $csv -SqlServer '$sqlserver'-Database '$database' -Table '$table' -Delimiter '$Delimiter' -First $First -Query '$query' -Batchsize $BatchSize -NotifyAfter $NotifyAfter $switches -shellswitch"
if ($SqlCredentialPath.length -gt 0) { $command += " -SqlCredentialPath $SqlCredentialPath"}
Write-Verbose "Switching to x86 shell, then switching back."
&"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" "$command"
return
}
}
# Do the first few lines contain the specified delimiter?
foreach ($file in $csv) {
try { $firstfewlines = Get-Content $file -First 3 -ErrorAction Stop } catch { throw "$file is in use." }
foreach ($line in $firstfewlines) {
if (($line -match $delimiter) -eq $false) { throw "Delimiter $delimiter not found in first row of $file." }
}
}
# If more than one csv specified, check to ensure number of columns match
if ($csv -is [system.array]){
$numberofcolumns = ((Get-Content $csv[0] -First 1 -ErrorAction Stop) -Split $delimiter).Count
foreach ($file in $csv) {
$firstline = Get-Content $file -First 1 -ErrorAction Stop
$newnumcolumns = ($firstline -Split $Delimiter).Count
if ($newnumcolumns -ne $numberofcolumns) { throw "Multiple csv file mismatch. Do both use the same delimiter and have the same number of columns?" }
}
}
# Automatically generate Table name if not specified, then prompt user to confirm
if ($table.length -eq 0) {
$table = [IO.Path]::GetFileNameWithoutExtension($csv[0])
$title = "Table name not specified."
$message = "Would you like to use the automatically generated name: $table"
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Uses table name $table for import."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Allows you to specify an alternative table name."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
if ($result -eq 1) {
do {$table = Read-Host "Please enter a table name"} while ($table.Length -eq 0)
}
}
# If the shell has switched, decode the $query string.
if ($shellswitch -eq $true) {
$bytes = [System.Convert]::FromBase64String($Query)
$query = [System.Text.Encoding]::UTF8.GetString($bytes)
$csv = $csv -Split ","
}
# Create columns based on first data row of first csv.
Write-Output "[*] Calculating column names and datatypes"
$columns = Get-Columns -Csv $Csv -Delimiter $Delimiter -FirstRowColumns $FirstRowColumns
if ($columns.count -gt 255 -and $safe -eq $true) {
throw "CSV must contain fewer than 256 columns."
}
$columntext = Get-ColumnText -Csv $Csv -Delimiter $Delimiter
# OLEDB method requires extra checks
if ($safe -eq $true) {
# Advanced SQL queries may not work (SqlBulkCopy likes a 1 to 1 mapping), so warn the user.
if ($Query -match "GROUP BY" -or $Query -match "COUNT") { Write-Warning "Script doesn't really support the specified query. This probably won't work, but will be attempted anyway." }
# Check for proper SQL syntax, which for the purposes of this module must include the word "table"
if ($query.ToLower() -notmatch "\bcsv\b") {
throw "SQL statement must contain the word 'csv'. Please see this module's documentation for more details."
}
# In order to ensure consistent results, a schema.ini file must be created.
# If a schema.ini already exists, it will be moved to TEMP temporarily.
Write-Verbose "Creating schema.ini"
$movedschemainis = Write-Schemaini -Csv $Csv -Columns $columns -Delimiter "$Delimiter" -FirstRowColumns $FirstRowColumns -ColumnText $columntext
}
# Display SQL Server Login info
if ($sqlcredential.count -gt 0) { $username = "SQL login $($SqlCredential.UserName)" }
else { $username = "Windows login $(whoami)" }
# Open Connection to SQL Server
Write-Output "[*] Logging into $sqlserver as $username"
$sqlconn = New-Object System.Data.SqlClient.SqlConnection
if ($SqlCredential.count -eq 0) {
$sqlconn.ConnectionString = "Data Source=$sqlserver;Integrated Security=True;Connection Timeout=3; Initial Catalog=master"
} else {
$sqlconn.ConnectionString = "Data Source=$sqlserver;User Id=$($SqlCredential.UserName); Password=$($SqlCredential.GetNetworkCredential().Password);Connection Timeout=3; Initial Catalog=master"
}
try { $sqlconn.Open() } catch { throw "Could not open SQL Server connection. Is $sqlserver online?" }
# Everything will be contained within 1 transaction, even creating a new table if required
# and truncating the table, if specified.
$transaction = $sqlconn.BeginTransaction()
# Ensure database exists
$sql = "select count(*) from master.dbo.sysdatabases where name = '$database'"
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
$dbexists = $sqlcmd.ExecuteScalar()
if ($dbexists -eq $false) { throw "Database does not exist on $sqlserver" }
Write-Output "[*] Database exists"
$sqlconn.ChangeDatabase($database)
# Ensure table exists
$sql = "select count(*) from $database.sys.tables where name = '$table'"
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
$tablexists = $sqlcmd.ExecuteScalar()
# Create the table if required. Remember, this will occur within a transaction, so if the script fails, the
# new table will no longer exist.
if ($tablexists -eq $false) {
Write-Output "[*] Table does not exist"
Write-Output "[*] Creating table"
New-SqlTable -Csv $Csv -Delimiter $Delimiter -Columns $columns -ColumnText $columntext -SqlConn $sqlconn -Transaction $transaction
} else { Write-Output "[*] Table exists" }
# Truncate if specified. Remember, this will occur within a transaction, so if the script fails, the
# truncate will not be committed.
if ($truncate -eq $true) {
Write-Output "[*] Truncating table"
$sql = "TRUNCATE TABLE [$table]"
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
try { $null = $sqlcmd.ExecuteNonQuery() } catch { Write-Warning "Could not truncate $table" }
}
# Get columns for column mapping
if ($columnMappings -eq $null) {
$olecolumns = ($columns | ForEach-Object { $_ -Replace "\[|\]" })
$sql = "select name from sys.columns where object_id = object_id('$table') order by column_id"
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand($sql, $sqlconn, $transaction)
$sqlcolumns = New-Object System.Data.DataTable
$sqlcolumns.Load($sqlcmd.ExecuteReader())
}
# Time to import!
$elapsed = [System.Diagnostics.Stopwatch]::StartNew()
# Process each CSV file specified
foreach ($file in $csv) {
# Dynamically set NotifyAfter if it wasn't specified
if ($notifyAfter -eq 0) {
if ($resultcount -is [int]) { $notifyafter = $resultcount/10 }
else { $notifyafter = 50000 }
}
# Setup bulk copy
Write-Output "[*] Starting bulk copy for $(Split-Path $file -Leaf)"
# Setup bulk copy options
$bulkCopyOptions = @()
$options = "TableLock","CheckConstraints","FireTriggers","KeepIdentity","KeepNulls","Default","Truncate"
foreach ($option in $options) {
$optionValue = Get-Variable $option -ValueOnly -ErrorAction SilentlyContinue
if ($optionValue -eq $true) { $bulkCopyOptions += "$option" }
}
$bulkCopyOptions = $bulkCopyOptions -join " & "
# Create SqlBulkCopy using default options, or options specified in command line.
if ($bulkCopyOptions.count -gt 1) { $bulkcopy = New-Object Data.SqlClient.SqlBulkCopy($oleconnstring, $bulkCopyOptions, $transaction) }
else { $bulkcopy = New-Object Data.SqlClient.SqlBulkCopy($sqlconn,"Default",$transaction) }
$bulkcopy.DestinationTableName = "[$table]"
$bulkcopy.bulkcopyTimeout = 0
$bulkCopy.BatchSize = $BatchSize
$bulkCopy.NotifyAfter = $NotifyAfter
if ($safe -eq $true) {
# Setup bulkcopy mappings
for ($columnid = 0; $columnid -lt $sqlcolumns.rows.count; $columnid++) {
$null = $bulkCopy.ColumnMappings.Add($olecolumns[$columnid], $sqlcolumns.rows[$columnid].ItemArray[0])
}
# Setup the connection string. Data Source is the directory that contains the csv.
# The file name is also the table name, but with a "#" instead of a "."
$datasource = Split-Path $file
$tablename = (Split-Path $file -leaf).Replace(".","#")
$oleconnstring = "Provider=$provider;Data Source=$datasource;Extended Properties='text';"
# To make command line queries easier, let the user just specify "csv" instead of the
# OleDbconnection formatted name (file.csv -> file#csv)
$sql = $Query -replace "\bcsv\b"," [$tablename]"
# Setup the OleDbconnection
$oleconn = New-Object System.Data.OleDb.OleDbconnection
$oleconn.ConnectionString = $oleconnstring
# Setup the OleDBCommand
$olecmd = New-Object System.Data.OleDB.OleDBCommand
$olecmd.Connection = $oleconn
$olecmd.CommandText = $sql
try { $oleconn.Open() } catch { throw "Could not open OLEDB connection." }
# Attempt to get the number of results so that a nice progress bar can be displayed.
# This takes extra time, and files over 100MB take too long, so just skip them.
if ($sql -match "GROUP BY") { "Query contains GROUP BY clause. Skipping result count." }
else { Write-Output "[*] Determining total rows to be copied. This may take a few seconds." }
if ($sql -match "\bselect top\b") {
try {
$split = $sql -split "\bselect top \b"
$resultcount = [int]($split[1].Trim().Split()[0])
Write-Output "[*] Attempting to fetch $resultcount rows"
} catch { Write-Warning "Couldn't determine total rows to be copied." }
} elseif ($sql -notmatch "GROUP BY") {
$filesize = (Get-ChildItem $file).Length / 1MB
if ($filesize -lt 100) {
try {
$split = $sql -split "\bfrom\b"
$sqlcount = "select count(*) from $($split[1])"
# Setup the OleDBCommand
$olecmd = New-Object System.Data.OleDB.OleDBCommand
$olecmd.Connection = $oleconn
$olecmd.CommandText = $sqlcount
$resultcount = [int]($olecmd.ExecuteScalar())
Write-Output "[*] $resultcount rows will be copied"
} catch { Write-Warning "Couldn't determine total rows to be copied" }
} else {
Write-Output "[*] File is too large for efficient result count; progress bar will not be shown."
}
}
}