Skip to content

Instantly share code, notes, and snippets.

@potatoqualitee
Created May 6, 2015 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save potatoqualitee/624a9c2dc4ca29ab370c to your computer and use it in GitHub Desktop.
Save potatoqualitee/624a9c2dc4ca29ab370c to your computer and use it in GitHub Desktop.
Query CSV with SQL
# See PowerShell Magazine article at .....
$jet = (New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -eq "Microsoft.Jet.OLEDB.4.0" }
if ($jet -eq $null) {
if ($env:Processor_Architecture -ne "x86") {
&"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe"
}
}
$csv = "$env:TEMP\top-tracks.csv"
Invoke-WebRequest http://git.io/vvzxA | Set-Content -Path $csv
$firstRowColumnNames = "Yes"
$delimiter = ","
$connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$(Split-Path $csv);Extended Properties='text;HDR=$firstRowColumnNames;';"
$tablename = (Split-Path $csv -leaf).Replace(".","#")
$sql = "SELECT TOP 20 SUM(playcount) AS playcount, artist from [$tablename] WHERE artist <> 'Fall Out Boy' GROUP BY artist HAVING SUM(playcount) > 4 ORDER BY SUM(playcount) DESC, artist"
# Setup connection and command
$conn = New-Object System.Data.OleDb.OleDbconnection
$conn.ConnectionString = $connstring
$conn.Open()
$cmd = New-Object System.Data.OleDB.OleDBCommand
$cmd.Connection = $conn
$cmd.CommandText = $sql
# Load into datatable
$dt = New-Object System.Data.DataTable
$dt.Load($cmd.ExecuteReader("CloseConnection"))
# Clean up
$cmd.dispose | Out-Null; $conn.dispose | Out-Null
# Output results
$dt | Format-Table -AutoSize
@midnightfreddie
Copy link

http://www.powershellmagazine.com/2015/05/12/natively-query-csv-files-using-sql-syntax-in-powershell/ is the source for this, for those left in suspense by the comment at line 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment