Skip to content

Instantly share code, notes, and snippets.

@benbrandt22
Created July 18, 2014 17:06
Show Gist options
  • Save benbrandt22/3606e55fe947a9227bd4 to your computer and use it in GitHub Desktop.
Save benbrandt22/3606e55fe947a9227bd4 to your computer and use it in GitHub Desktop.
Objectify - Converts tab-delimited table in the clipboard into a List of objects in C# code
# Objectify.ps1
# Ben Brandt - July 18, 2014
# Turns a tab-delimited table from the clipboard text, and converts it to a List of objects in C# code.
# Useful for taking data copied from SQL Management Studio (with Headers) and converting it to in-memory objects for use as test data.
function Get-ClipboardText()
{
Add-Type -AssemblyName System.Windows.Forms
$tb = New-Object System.Windows.Forms.TextBox
$tb.Multiline = $true
$tb.Paste()
return $tb.Text
}
filter isNumeric() {
$out = 0
$isNum = [System.Int32]::TryParse($_, [ref]$out)
return $isNum
}
Clear-Host
$cbText = Get-ClipboardText
$lines = $cbText.Split("`r`n") | where { ![string]::IsNullOrEmpty($_) }
Write-Host 'ClipBoard Text:'
Write-Host '--------------------------------------------------'
Write-Host $cbText
Write-Host ''
Write-Host '--------------------------------------------------'
$firstLine = $lines[0];
$columns = $firstLine.Split("`t")
Write-Host "Detected Column Headers ($($columns.Count)):"
$columns | Foreach {
Write-Host " [$_]"
}
Write-Host '--------------------------------------------------'
Write-Host 'C# Object Code:'
Write-Host ''
Write-Host "var objects = new List<dynamic> {"
$lines | select -skip 1 | Foreach {
$thisLine = $_
$thisLineValues = $thisLine.Split("`t")
$keyValuePairs = @();
for ($i=0; $i -lt $columns.Count; $i++){
$valueOutput = $thisLineValues[$i]
If($valueOutput | isNumeric)
{
$valueOutput = $valueOutput
} Else {
#escape double quotes
$valueOutput = $valueOutput -replace """", "\"""
#surround with double quotes
$valueOutput = """$valueOutput"""
}
$kvp = [string]::Format("{0} = {1}", $columns[$i], $valueOutput )
$keyValuePairs += $kvp
}
$outputLine = " new { "
$outputLine += $keyValuePairs -join ", "
$outputLine += " },"
Write-Host $outputLine
}
Write-Host "};"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment