Functions/Out-DataTableToFile.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
function Out-DataTableToFile {
    <#
    .SYNOPSIS
        Dump a datatable to CSV-file OR XML-file
    .DESCRIPTION
        Not much to add. It's fairly simple.
    .PARAMETER CSVseparator
           Character to use for CSV separation.
    .PARAMETER CSVnoheader
        Do not export header (column names) to CSV.
    .PARAMETER Header
        Use custom header (NOT column names) in CSV.
    .PARAMETER Encoding
        Specifies the type of character encoding used in the file. Valid values are "Unicode", "UTF7", "UTF8", "UTF32","ASCII", "BigEndianUnicode", "Default", and "OEM".
    .PARAMETER FileName
        Name of target file fo export.
    .PARAMETER Xml
        Export to XML instead of CSV.
    .NOTES
        Author: Jack Olsson
        Date: 2016-04-21
    }
    #>

    param (
       [Parameter(Mandatory=$true,
                  ValueFromPipeline=$true,
                  ValueFromPipelineByPropertyName=$true)]
       [System.Data.Datatable]$DataTable,
       [Parameter(Mandatory=$true,              
                  ValueFromPipelineByPropertyName=$true)]
       [string]$FileName,   
       [string]$CSVseparator,
       [switch]$CSVnoheader,
       [string]$Header,
       [string]$Encoding,
       [switch]$xml
       
    )
    
    Begin {
    }
    Process {
       Write-Verbose $DataTable.TableName
        if ($xml.IsPresent) {
            ($DataTable | ConvertTo-XML -NoTypeInformation).Save($FileName)    
        } else {
            if ($CSVnoheader.IsPresent) {
                ($DataTable | ConvertTo-Csv -Delimiter $CSVseparator -NoTypeInformation) -replace "`"", "" |  Select-Object -Skip 1 | `
                    Out-File -Encoding $Encoding -Force $FileName
            } elseif (-not [string]::IsNullOrEmpty($Header)) {
                $Header | Out-File -Encoding $Encoding -Force $FileName
                ($DataTable | ConvertTo-Csv -Delimiter $CSVseparator -NoTypeInformation) -replace "`"", "" |  Select-Object -Skip 1 | `
                    Out-File -Encoding $Encoding -Append $FileName 
     
            } else {
                ($DataTable | ConvertTo-Csv -Delimiter $CSVseparator -NoTypeInformation) -replace "`"", "" | `
                    Out-File -Encoding $Encoding -Force $FileName
            }
        }
    }
    
    End {
    }
}