Skip to content

Instantly share code, notes, and snippets.

@talatham
Last active October 24, 2018 11:22
Show Gist options
  • Save talatham/8259d3f91a6fb8cb3c9cfb15a76eba44 to your computer and use it in GitHub Desktop.
Save talatham/8259d3f91a6fb8cb3c9cfb15a76eba44 to your computer and use it in GitHub Desktop.
Export a PowerShell datagrid to a CSV file
function export-DGV2CSV ([Windows.Forms.DataGridView] $grid, [String] $File)
<#
.SYNOPSIS
Export basic datagrid to CSV file
.PARAMETER grid
Datagrid object
.PARAMETER file
Path to CSV file
#>
{
if ($grid.RowCount -eq 0) { return } # nothing to do
$row = New-Object Windows.Forms.DataGridViewRow
$sw = new-object System.IO.StreamWriter($File)
#Write header line
$sw.WriteLine( ($grid.Columns | % { $_.HeaderText } ) -join ',' )
#Export contents
$grid.Rows | % {
$sw.WriteLine(
($_.Cells | % { $_.Value }) -join ','
)
}
$sw.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment