-
Notifications
You must be signed in to change notification settings - Fork 104
/
Convert-CsvToPsDt.ps1
79 lines (68 loc) · 2.37 KB
/
Convert-CsvToPsDt.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
Function Convert-CsvToPsDt
{
<#
.SYNOPSIS
This function can be used to convert a CSV into PowerShell code
that creates a data table that mirrors the CSV structure and content.
.PARAMETER $Infile
The csv input file path.
.PARAMETER $Outfile
The output file path.
.EXAMPLE
PS C:\> Convert-CsvToPsDt -Infile c:\temp\serverinfo.csv -Outfile c:\temp\createmydatatable.ps1
.NOTES
Author: Scott Sutherland (@_nullbind)
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true,
HelpMessage = 'The csv input file path.')]
[string]$Infile,
[Parameter(Mandatory = $true,
HelpMessage = 'The output file path.')]
[string]$Outfile = ".\MyPsDataTable.ps1"
)
# Test file path
if(Test-Path $Infile)
{
Write-Output "[+] $Infile is accessible."
}else{
write-Output "[-] $Infile is not accessible, aborting."
break
}
# Import CSV
Write-Output "[+] Importing csv file."
$MyCsv = Import-Csv $Infile
# Get list of columns
Write-Output "[+] Paring columns."
$MyCsvColumns = $MyCsv | Get-Member | Where-Object MemberType -like "NoteProperty" | Select-Object Name -ExpandProperty Name
# Print data table creation
Write-Output "[+] Writing data table object to $Outfile."
write-output '$MyTable = New-Object System.Data.DataTable' | Out-File $Outfile
# Print columns creation
Write-Output "[+] Writing data table columns to $Outfile."
$MyCsvColumns |
ForEach-Object {
write-Output "`$null = `$MyTable.Columns.Add(`"$_`")" | Out-File $Outfile -Append
}
# Print data rows
Write-Output "[+] Writing data table rows to $Outfile."
$MyCsv |
ForEach-Object {
# Create a value contain row data
$CurrentRow = $_
$PrintRow = ""
$MyCsvColumns |
ForEach-Object{
$GetValue = $CurrentRow | Select-Object $_ -ExpandProperty $_
if($PrintRow -eq ""){
$PrintRow = "`"$GetValue`""
}else{
$PrintRow = "$PrintRow,`"$GetValue`""
}
}
# Print row addition
write-Output "`$null = `$MyTable.Rows.Add($PrintRow)" | Out-File $Outfile -Append
}
Write-Output "[+] All done."
}