Created
May 6, 2015 04:11
-
-
Save potatoqualitee/624a9c2dc4ca29ab370c to your computer and use it in GitHub Desktop.
Query CSV with SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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