Skip to content

Instantly share code, notes, and snippets.

@vexx32
Last active May 6, 2019 19:51
Show Gist options
  • Select an option

  • Save vexx32/606b5baf4cae2fe6553ab625d7937ada to your computer and use it in GitHub Desktop.

Select an option

Save vexx32/606b5baf4cae2fe6553ab625d7937ada to your computer and use it in GitHub Desktop.
function Invoke-SqlSelect {
<#
.DESCRIPTION
This is a re-usable function that makes a connection to the database and retrieves a result set.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)]
[string]
$Command,
[Parameter(Mandatory, Position = 1)]
[Alias('ServerName')]
[string]
$ComputerName,
[Parameter(Mandatory, Position = 2)]
[string]
$DBName
)
$ResultDataSet = [System.Data.DataSet]::new()
$sqlConn = [System.Data.SqlClient.SqlConnection]::new()
$sqlConn.ConnectionString = "Server=$ComputerName;Database=$DBName;Integrated Security=SSPI"
try {
$sqlConn.Open()
$sqlDataAdapter = [System.Data.SqlClient.SqlDataAdapter]::new()
$sqlCommand = [System.Data.SqlClient.SqlCommand]::new()
if($sqlConn.State -eq 1) {
$sqlCommand.CommandText = $command
$SqlCommand.Connection = $sqlConn
$sqlCommand.CommandTimeout = 0
$sqlDataAdapter.SelectCommand = $sqlCommand
$sqlDataAdapter.Fill($ResultDataSet,"result") | Out-Null
}
}
finally {
$sqlConn.Close()
}
$ResultDataSet
}
#this is the sql run to get the data
$Query = Get-Content -Path "P:\ReportScheduler\SCRIPTS\RelayBillPlacement.sql"
Write-Host $Query
$results = Execute-SqlSelect $Query "my server" "my database"
$OutputFolder = "c:\downloads\"
$OutputFile = [System.DateTime]::Today.AddDays(-1).ToString("MMddyyyy") + "_LPH_fauquier_patinfo.dat"
# Create the file with ONLY the header line
$OutputFile = Join-Path -Path $OutputFolder -ChildPath $OutputFile
"16960|Fauquier Hospital|Fauquier Hospital|"+(Get-Date).ToString('MM/dd/yyyy')+"|06:00:00" |
Set-Content -Path $OutputFile
# Convert the data into a CSV string in memory and remove double quotes
$CsvData = ($Results.Tables[0] | ConvertTo-Csv -NoTypeInformation -Delimiter '|') -replace '"'
#add the data to the file which only contains the header row
$CsvData | Add-Content -Path $OutputFile
### DONE ###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment