Skip to content

Instantly share code, notes, and snippets.

@koohq
Created November 3, 2017 03:55
Show Gist options
  • Save koohq/fc2a383c524a43985eccb0e61a18c404 to your computer and use it in GitHub Desktop.
Save koohq/fc2a383c524a43985eccb0e61a18c404 to your computer and use it in GitHub Desktop.
A helper script for query to MSSQL by PowerShell
<##
# Query.ps1
#
# (c) 2016 koohq. Licensed under CC0.
# https://creativecommons.org/publicdomain/zero/1.0/legalcode
#>
function Use
{
[CmdletBinding()]
[OutputType()]
param(
[Parameter(mandatory)]
[IDisposable]$obj,
[Parameter(mandatory)]
[scriptblock]$sb
)
try
{
& $sb
}
finally
{
if ($null -ne $obj)
{
$obj.Dispose()
}
}
}
function Query-TSQL
{
[CmdletBinding()]
[OutputType([PSCustomObject[]])]
param(
[Parameter(mandatory)]
[string]$ConnStr,
[Parameter(mandatory)]
[string]$Sql
)
Use ($conn = New-Object System.Data.SqlClient.SqlConnection($ConnStr)) {
$conn.Open()
Use ($cmd = New-Object System.Data.SqlClient.SqlCommand($Sql, $conn)) {
Use ($reader = $cmd.ExecuteReader()) {
$rows = @()
$colNames = @()
while ($reader.Read())
{
if ($colNames.Length -eq 0) { $colNames = 0..($reader.FieldCount - 1) | foreach { $reader.GetName($_) } }
$row = [PSCustomObject]@{}
$colNames | foreach { $row | Add-Member -NotePropertyName $_ -NotePropertyValue $reader[$_] }
$rows += $row
}
$rows
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment