Minor tidying. Making case consistent, and various things analyzer friendly; added Timeout to Send-SQL...,

This commit is contained in:
jhoneill
2018-05-13 17:35:31 +01:00
parent b8cc7f163f
commit 6a53d3ddc9
5 changed files with 29 additions and 23 deletions

View File

@@ -1,4 +1,4 @@
 ipmo C:\Users\mcp\Documents\GitHub\ImportExcel\ImportExcel.psd1 -Force -Verbose  Import-Module -name ImportExcel -Force -Verbose
$sql = @" $sql = @"
SELECT rootfile.baseName , rootfile.extension , Image.fileWidth AS width , image.fileHeight AS height , SELECT rootfile.baseName , rootfile.extension , Image.fileWidth AS width , image.fileHeight AS height ,

View File

@@ -19,7 +19,7 @@ function Export-ExcelSheet {
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path $xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path
$workbook = $xl.Workbook $workbook = $xl.Workbook
$targetSheets = $workbook.Worksheets | Where {$_.Name -Match $SheetName} $targetSheets = $workbook.Worksheets | Where-Object {$_.Name -Match $SheetName}
$params = @{} + $PSBoundParameters $params = @{} + $PSBoundParameters
$params.Remove("OutputPath") $params.Remove("OutputPath")

View File

@@ -14,7 +14,7 @@ Param (
#Path to the Excel file whose chars we will export. #Path to the Excel file whose chars we will export.
$Path = "C:\Users\public\Documents\stats.xlsx", $Path = "C:\Users\public\Documents\stats.xlsx",
#If specified, output file objects representing the image files. #If specified, output file objects representing the image files.
[switch]$passthru, [switch]$Passthru,
#Format to write - JPG by default #Format to write - JPG by default
[ValidateSet("JPG","PNG","GIF")] [ValidateSet("JPG","PNG","GIF")]
$OutputType = "JPG", $OutputType = "JPG",
@@ -23,15 +23,14 @@ Param (
) )
#if no output folder was specified, set destination to the folder where the Excel file came from #if no output folder was specified, set destination to the folder where the Excel file came from
if (-not $Destination) {$Destination = Split-Path -Path $path -Parent } if (-not $Destination) {$Destination = Split-Path -Path $Path -Parent }
#Call up Excel and tell it to open the file. #Call up Excel and tell it to open the file.
try { $excelApp = New-Object -ComObject "Excel.Application" } try { $excelApp = New-Object -ComObject "Excel.Application" }
catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return } catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return }
try { $excelWorkBook = $excelApp.Workbooks.Open($path) } try { $excelWorkBook = $excelApp.Workbooks.Open($Path) }
catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return } catch { Write-Warning -Message "Could not Open $Path." ; return }
#For each worksheet, for each chart, jump to the chart, create a filename of "WorksheetName_ChartTitle.jpg", and export the file. #For each worksheet, for each chart, jump to the chart, create a filename of "WorksheetName_ChartTitle.jpg", and export the file.
foreach ($excelWorkSheet in $excelWorkBook.Worksheets) { foreach ($excelWorkSheet in $excelWorkBook.Worksheets) {
@@ -41,11 +40,12 @@ foreach ($excelWorkSheet in $excelWorkBook.Worksheets) {
$excelApp.Goto($excelchart.TopLeftCell,$true) $excelApp.Goto($excelchart.TopLeftCell,$true)
$imagePath = Join-Path -Path $Destination -ChildPath ($excelWorkSheet.Name + "_" + ($excelchart.Chart.ChartTitle.Text -split "\s\d\d:\d\d,")[0] + ".$OutputType") $imagePath = Join-Path -Path $Destination -ChildPath ($excelWorkSheet.Name + "_" + ($excelchart.Chart.ChartTitle.Text -split "\s\d\d:\d\d,")[0] + ".$OutputType")
if ( $excelchart.Chart.Export($imagePath, $OutputType, $false) ) { # Export returs true/false for success/failure if ( $excelchart.Chart.Export($imagePath, $OutputType, $false) ) { # Export returs true/false for success/failure
if ($passThru) {Get-Item -Path $imagePath } # when succesful return a file object (-passthru) or print a verbose message, write warning for any failures if ($Passthru) {Get-Item -Path $imagePath } # when succesful return a file object (-Passthru) or print a verbose message, write warning for any failures
else {Write-Verbose -Message "Exported $imagePath"} else {Write-Verbose -Message "Exported $imagePath"}
} }
else {Write-Warning -Message "Failure exporting $imagePath" } else {Write-Warning -Message "Failure exporting $imagePath" }
} }
} }
$excelApp.DisplayAlerts = $false
$excelWorkBook.Close($false,$null,$null)
$excelApp.Quit() $excelApp.Quit()

View File

@@ -1,5 +1,7 @@
Function Send-SQLDataToExcel { Function Send-SQLDataToExcel {
<# [CmdLetBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","")]
<#
.Synopsis .Synopsis
Runs a SQL query and inserts the results into an ExcelSheet, more efficiently than sending it via Export-Excel Runs a SQL query and inserts the results into an ExcelSheet, more efficiently than sending it via Export-Excel
.Description .Description
@@ -23,7 +25,7 @@
#> #>
param ( param (
#Database connection string; either DSN=ODBC_Data_Source_Name, a full odbc or SQL Connection string, or the name of a SQL server #Database connection string; either DSN=ODBC_Data_Source_Name, a full odbc or SQL Connection string, or the name of a SQL server
[Parameter(ParameterSetName="SQLConnection", Mandatory=$true)] [Parameter(ParameterSetName="SQLConnection", Mandatory=$true)]
@@ -41,6 +43,9 @@
#The SQL query to run #The SQL query to run
[Parameter(Mandatory=$true)] [Parameter(Mandatory=$true)]
[string]$SQL, [string]$SQL,
#Override the default query time of 30 seconds.
[int]$QueryTimeout,
#File name for the Excel File
$Path, $Path,
[String]$WorkSheetname = 'Sheet1', [String]$WorkSheetname = 'Sheet1',
[Switch]$KillExcel, [Switch]$KillExcel,
@@ -92,9 +97,9 @@
#We were either given a session object or a connection string (with, optionally a MSSQLServer parameter) #We were either given a session object or a connection string (with, optionally a MSSQLServer parameter)
# If we got -MSSQLServer, create a SQL connection, if we didn't but we got -Connection create an ODBC connection # If we got -MSSQLServer, create a SQL connection, if we didn't but we got -Connection create an ODBC connection
if ($MsSQLserver) { if ($MsSQLserver) {
if ($connection -notmatch "=") {$Connection = "server=$Connection;trusted_connection=true;timeout=60"} if ($Connection -notmatch "=") {$Connection = "server=$Connection;trusted_connection=true;timeout=60"}
$Session = New-Object -TypeName System.Data.SqlClient.SqlConnection -ArgumentList $Connection $Session = New-Object -TypeName System.Data.SqlClient.SqlConnection -ArgumentList $Connection
if ($Session.State -ne 'Open') {$session.Open()} if ($Session.State -ne 'Open') {$Session.Open()}
if ($DataBase) {$Session.ChangeDatabase($DataBase) } if ($DataBase) {$Session.ChangeDatabase($DataBase) }
} }
elseif ($Connection) { elseif ($Connection) {
@@ -102,30 +107,31 @@
} }
#A session was either passed in or just created. If it's a SQL one make a SQL DataAdapter, otherwise make an ODBC one #A session was either passed in or just created. If it's a SQL one make a SQL DataAdapter, otherwise make an ODBC one
if ($Session.gettype().name -match "SqlConnection") { if ($Session.GetType().name -match "SqlConnection") {
$dataAdapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter -ArgumentList ( $dataAdapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter -ArgumentList (
New-Object -TypeName System.Data.SqlClient.SqlCommand -ArgumentList $sql, $Session) New-Object -TypeName System.Data.SqlClient.SqlCommand -ArgumentList $SQL, $Session)
} }
else { else {
$dataAdapter = New-Object -TypeName System.Data.Odbc.OdbcDataAdapter -ArgumentList ( $dataAdapter = New-Object -TypeName System.Data.Odbc.OdbcDataAdapter -ArgumentList (
New-Object -TypeName System.Data.Odbc.OdbcCommand -ArgumentList $sql, $Session ) New-Object -TypeName System.Data.Odbc.OdbcCommand -ArgumentList $SQL, $Session )
} }
if ($QueryTimeout) {$dataAdapter.SelectCommand.CommandTimeout = $ServerTimeout}
#Both adapter types output the same kind of table, create one and fill it from the adapter #Both adapter types output the same kind of table, create one and fill it from the adapter
$dataTable = New-Object -TypeName System.Data.DataTable $dataTable = New-Object -TypeName System.Data.DataTable
$rowCount = $dataAdapter.fill($dataTable) $rowCount = $dataAdapter.fill($dataTable)
Write-Verbose "Query returned $rowcount row(s)" Write-Verbose -Message "Query returned $rowCount row(s)"
#ExportExcel user a -NoHeader parameter so that's what we use here, but needs to be the other way around. #ExportExcel user a -NoHeader parameter so that's what we use here, but needs to be the other way around.
$PrintHeaders = -not $NoHeader $printHeaders = -not $NoHeader
if ($Title) {$r = $StartRow +1 } if ($Title) {$r = $StartRow +1 }
else {$r = $StartRow} else {$r = $StartRow}
#Get our Excel sheet and fill it with the data #Get our Excel sheet and fill it with the data
$excelPackage = Export-Excel -Path $Path -WorkSheetname $WorkSheetname -PassThru $excelPackage = Export-Excel -Path $Path -WorkSheetname $WorkSheetname -PassThru
$excelPackage.Workbook.Worksheets[$WorkSheetname].Cells[$r,$StartColumn].LoadFromDataTable($dataTable, $PrintHeaders ) | Out-Null $excelPackage.Workbook.Worksheets[$WorkSheetname].Cells[$r,$StartColumn].LoadFromDataTable($dataTable, $printHeaders ) | Out-Null
#Call export-excel with any parameters which don't relate to the SQL query #Call export-excel with any parameters which don't relate to the SQL query
"Connection", "Database" , "Session", "MsSQLserver", "Destination" , "sql" ,"Path" | foreach-object {$null = $PSBoundParameters.Remove($_) } "Connection", "Database" , "Session", "MsSQLserver", "Destination" , "SQL" ,"Path" | ForEach-Object {$null = $PSBoundParameters.Remove($_) }
Export-Excel -ExcelPackage $excelPackage @PSBoundParameters Export-Excel -ExcelPackage $excelPackage @PSBoundParameters
#If we were not passed a session close the session we created. #If we were not passed a session close the session we created.

View File

@@ -168,7 +168,7 @@
} }
#if font colour was specified, set it on changed properties where the same key appears in both sheets. #if font colour was specified, set it on changed properties where the same key appears in both sheets.
if ($diff -and $FontColor -and ($propList -contains $Key) ) { if ($diff -and $FontColor -and ($propList -contains $Key) ) {
$updates = $diff.where({$_.SideIndicator -ne "=="}) | Group-object -Property $Key | where {$_.count -eq 2} $updates = $diff.where({$_.SideIndicator -ne "=="}) | Group-object -Property $Key | Where-Object {$_.count -eq 2}
if ($updates) { if ($updates) {
$XL1 = Open-ExcelPackage -path $Referencefile $XL1 = Open-ExcelPackage -path $Referencefile
if ($oneFile ) {$xl2 = $xl1} if ($oneFile ) {$xl2 = $xl1}