Linted with the updated PSScriptAnalyzer.

This commit is contained in:
jhoneill
2019-04-30 13:28:52 -07:00
parent 77ef2ebc40
commit 6c7f00b031
33 changed files with 220 additions and 182 deletions

View File

@@ -185,7 +185,7 @@
$Address = "$($Address.Row):$($Address.Row)"
}
elseif ($Address -is [OfficeOpenXml.ExcelColumn]) {
$Address = [OfficeOpenXml.ExcelAddress]::new(1,$address.ColumnMin,1,$address.ColumnMax).Address -replace '1',''
$Address = (New-Object 'OfficeOpenXml.ExcelAddress' @(1, $address.ColumnMin, 1, $address.ColumnMax).Address) -replace '1',''
if ($Address -notmatch ':') {$Address = "$Address`:$Address"}
}
if ( $Address -is [string] -and $Address -match "!") {$Address = $Address -replace '^.*!',''}

View File

@@ -10,7 +10,7 @@ $PSVersionTable.PSVersion
## Create the zip before the tests run
## Otherwise the EPPlus.dll is in use after the Pester run
$ModuleVersion = (Get-Content -Raw .\ImportExcel.psd1) | Invoke-Expression | ForEach-Object ModuleVersion
$ModuleVersion = (Invoke-Command -ScriptBlock ([scriptblock]::Create((Get-Content -Raw .\ImportExcel.psd1)))).moduleVersion
if (!$DontCreateZip) {
$dest = "ImportExcel-{0}-{1}.zip" -f $ModuleVersion, (Get-Date).ToString("yyyyMMddHHmmss")

View File

@@ -84,9 +84,9 @@
.PARAMETER RangeName
Makes the data in the worksheet a named range.
.PARAMETER TableName
Makes the data in the worksheet a table with a name, and applies a style to it. Name must not contain spaces.
Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If a style is specified without a name, table1, table2 etc. will be used.
.PARAMETER TableStyle
Selects the style for the named table - defaults to 'Medium6'.
Selects the style for the named table - if a name is specified without a style, 'Medium6' is used as a default.
.PARAMETER BarChart
Creates a "quick" bar chart using the first text column as labels and the first numeric column as values
.PARAMETER ColumnChart
@@ -418,15 +418,15 @@
.LINK
https://github.com/dfinke/ImportExcel
#>
[CmdletBinding(DefaultParameterSetName = 'Default')]
[CmdletBinding(DefaultParameterSetName = 'Now')]
[OutputType([OfficeOpenXml.ExcelPackage])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
Param(
[Parameter(ParameterSetName = "Default", Position = 0)]
[Parameter(ParameterSetName = "Table" , Position = 0)]
[Parameter(Mandatory = $true, ParameterSetName = "Path", Position = 0)]
[String]$Path,
[Parameter(Mandatory = $true, ParameterSetName = "PackageDefault")]
[Parameter(Mandatory = $true, ParameterSetName = "PackageTable")]
[Parameter(Mandatory = $true, ParameterSetName = "Package")]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
[Parameter(ValueFromPipeline = $true)]
[Alias('TargetData')]
@@ -462,8 +462,8 @@
[Switch]$FreezeFirstColumn,
[Switch]$FreezeTopRowFirstColumn,
[Int[]]$FreezePane,
[Parameter(ParameterSetName = 'Default')]
[Parameter(ParameterSetName = 'PackageDefault')]
[Switch]$AutoFilter,
[Switch]$BoldTopRow,
[Switch]$NoHeader,
@@ -478,11 +478,11 @@
elseif ($_[0] -notmatch '[a-z]') { throw 'Tablename starts with an invalid character.' }
else { $true }
})]
[Parameter(ParameterSetName = 'Table' , Mandatory = $true, ValueFromPipelineByPropertyName)]
[Parameter(ParameterSetName = 'PackageTable' , Mandatory = $true, ValueFromPipelineByPropertyName)]
[String]$TableName,
[Parameter(ParameterSetName = 'Table')]
[Parameter(ParameterSetName = 'PackageTable')]
[OfficeOpenXml.Table.TableStyles]$TableStyle,
[Switch]$Barchart,
[Switch]$PieChart,
@@ -793,9 +793,12 @@
Add-ExcelName -RangeName $targetRangeName -Range $ws.Cells[$targetRow, ($StartColumn + $c ), $LastRow, ($StartColumn + $c )]
try {#this test can throw with some names, surpress any error
if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress(($targetRangeName -replace '\W' , '_' ))) {
Write-Warning "AutoNameRange: Property name '$targetRangeName' is also a valid Excel address and may cause issues. Consider renaming the property name."
Write-Warning -Message "AutoNameRange: Property name '$targetRangeName' is also a valid Excel address and may cause issues. Consider renaming the property."
}
}
Catch {
Write-Warning -Message "AutoNameRange: Testing '$targetRangeName' caused an error. This should be harmless, but a change of property name may be needed.."
}
} Catch {}
}
}
catch {Write-Warning -Message "Failed adding named ranges to worksheet '$WorksheetName': $_" }
@@ -803,14 +806,17 @@
#Empty string is not allowed as a name for ranges or tables.
if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName}
#Allow table to be inserted by specifying Name, or Style or both; only process autoFilter if there is no table (they clash).
if ($TableName) {
if ($PSBoundParameters.ContainsKey('TableStyle')) {
Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle
}
else {Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName}
}
if ($AutoFilter) {
elseif ($PSBoundParameters.ContainsKey('TableStyle')) {
Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName "" -TableStyle $TableStyle
}
elseif ($AutoFilter) {
try {
$ws.Cells[$dataRange].AutoFilter = $true
Write-Verbose -Message "Enabled autofilter. "
@@ -1235,7 +1241,7 @@ function Select-Worksheet {
}
}
Function Add-ExcelName {
function Add-ExcelName {
<#
.SYNOPSIS
Adds a named-range to an existing Excel worksheet.
@@ -1299,9 +1305,8 @@ function Add-ExcelTable {
#The range of cells to assign to a table.
[Parameter(Mandatory=$true)]
[OfficeOpenXml.ExcelRange]$Range,
#The name for the Table - this should be unqiue in the Workbook.
[Parameter(Mandatory=$true)]
[String]$TableName,
#The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty.
[String]$TableName = "",
#The Style for the table, by default "Medium6" is used
[OfficeOpenXml.Table.TableStyles]$TableStyle = 'Medium6',
#By default the header row is shown - it can be turned off with -ShowHeader:$false.
@@ -1324,12 +1329,16 @@ function Add-ExcelTable {
[Switch]$PassThru
)
try {
if ($TableName -eq "" -or $null -eq $TableName) {
$tbl = $Range.Worksheet.Tables.Add($Range, "")
}
else {
if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress($TableName)) {
Write-Warning -Message "$tableName reads as an Excel address, and so is not allowed as a table name."
Write-Warning -Message "$TableName reads as an Excel address, and so is not allowed as a table name."
return
}
if ($tableName -notMatch '^[A-Z]') {
Write-Warning -Message "$tableName is not allowed as a table name because it does not begin with a letter."
if ($TableName -notMatch '^[A-Z]') {
Write-Warning -Message "$TableName is not allowed as a table name because it does not begin with a letter."
return
}
if ($TableName -match "\W") {
@@ -1349,7 +1358,8 @@ function Add-ExcelTable {
}
else {
$tbl = $ws.Tables.Add($Range, $TableName)
Write-Verbose -Message "Defined table '$TableName' at $($Range.Address)"
Write-Verbose -Message "Defined table '$($tbl.Name)' at $($Range.Address)"
}
}
#it seems that show total changes some of the others, so the sequence matters.
if ($PSBoundParameters.ContainsKey('ShowHeader')) {$tbl.ShowHeader = [bool]$ShowHeader}
@@ -1358,7 +1368,7 @@ function Add-ExcelTable {
foreach ($k in $TotalSettings.keys) {
if (-not $tbl.Columns[$k]) {Write-Warning -Message "Table does not have a Column '$k'."}
elseif ($TotalSettings[$k] -notin @("Average", "Count", "CountNums", "Max", "Min", "None", "StdDev", "Sum", "Var") ) {
Write-wanring "'$($TotalSettings[$k])' is not a valid total function."
Write-Warning -Message "'$($TotalSettings[$k])' is not a valid total function."
}
else {$tbl.Columns[$k].TotalsRowFunction = $TotalSettings[$k]}
}

View File

@@ -96,7 +96,7 @@ function ConvertFrom-ExcelColumnName {
$sum
}
ipmo .\ImportExcel.psd1 -Force
Import-Module .\ImportExcel.psd1 -Force
#Get-ExcelTableName .\testTable.xlsx | Get-ExcelTable .\testTable.xlsx
Get-ExcelTable .\testTable.xlsx Table3

View File

@@ -10,7 +10,7 @@ function Import-Html {
)
$xlFile = [System.IO.Path]::GetTempFileName() -replace "tmp","xlsx"
rm $xlFile -ErrorAction Ignore
Remove-Item $xlFile -ErrorAction Ignore
Write-Verbose "Exporting to Excel file $($xlFile)"

View File

@@ -48,6 +48,7 @@ if ($PSVersionTable.PSVersion.Major -ge 5) {
. $PSScriptRoot\Plot.ps1
Function New-Plot {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification='New-Plot does not change system state')]
Param()
[PSPlot]::new()
@@ -296,7 +297,7 @@ function Import-Excel {
.SYNOPSIS
Create objects containing the column number and the column name for each of the different header types.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification="Name would be incorrect, and command is not exported")]
Param (
[Parameter(Mandatory)]
[Int[]]$Columns,

View File

@@ -1,3 +1,3 @@
if((Get-Module -list ImportExcel) -eq $null) {
if($null -eq (Get-Module -ListAvailable ImportExcel) ) {
Import-Module $PSScriptRoot\ImportExcel.psd1 -force
}

View File

@@ -375,6 +375,8 @@ Function Merge-MultipleSheets {
the key; in this version the row numbers are hidden.
#>
[cmdletbinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification="MultipleSheet would be incorrect")]
#[Alias("Merge-MulipleSheets")] #There was a spelling error in the first release. This was there to ensure things didn't break but intelisense gave the alias first.
param (
#Paths to the files to be merged. Files are also accepted

View File

@@ -27,6 +27,7 @@ function New-ConditionalFormattingIconSet {
Add-Add-ConditionalFormatting
New-ConditionalText
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')]
param(
[Parameter(Mandatory=$true)]
$Range,

View File

@@ -42,8 +42,8 @@ function New-ConditionalText {
Add-Add-ConditionalFormatting
New-ConditionalFormattingIconSet
#>
[cmdletbinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')]
param(
#[Parameter(Mandatory=$true)]
[Alias("ConditionValue")]

View File

@@ -97,6 +97,7 @@
#>
[Alias("New-ExcelChart")] #This was the former name. The new name reflects that we are defining a chart, not making one in the workbook.
[cmdletbinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')]
param(
$Title = "Chart Title",
$Header,

View File

@@ -1,3 +1,5 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='New*', Justification='Does not change system State')]
param()
function New-PSItem {
$totalArgs = $args.Count

View File

@@ -312,6 +312,7 @@ function New-PivotTableDefinition {
This is a re-work of one of the examples in Export-Excel - instead of writing out the pivot definition hash table it is built by calling New-PivotTableDefinition.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system State')]
param(
[Parameter(Mandatory)]
[Alias("PivtoTableName")]#Previous typo - use alias to avoid breaking scripts

View File

@@ -15,7 +15,8 @@
C:\> dir c:\reports\*.xlsx | Remove-WorkSheet
Removes 'Sheet1' from all the xlsx files in the c:\reports directory
#>
#>
[cmdletbinding(SupportsShouldProcess=$true)]
param(
# [Parameter(ValueFromPipelineByPropertyName)]
[Parameter(ValueFromPipelineByPropertyName)]
@@ -34,9 +35,10 @@
if ($pkg) {
foreach ($wsn in $WorksheetName) {
if ($PSCmdlet.ShouldProcess($FullName,"Remove Sheet $wsn")) {
$pkg.Workbook.Worksheets.Delete($wsn)
}
}
Close-ExcelPackage -ExcelPackage $pkg -Show:$Show
}
}

View File

@@ -90,6 +90,8 @@
Export-Excel
#>
[CmdletBinding(DefaultParameterSetName="none")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Justification="Allowed to use DBSessions Global variable from GETSQL Module")]
param (
[Parameter(ParameterSetName="SQLConnection", Mandatory=$true)]
[Parameter(ParameterSetName="ODBCConnection", Mandatory=$true)]

View File

@@ -1,4 +1,7 @@
function Set-CellStyle {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='Set*', Justification='Does not change system state')]
param()
function Set-CellStyle {
param(
$WorkSheet,
$Row,

View File

@@ -44,6 +44,8 @@
[cmdletbinding()]
[Alias("Set-Column")]
[OutputType([OfficeOpenXml.ExcelColumn],[String])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="Variables created for script block which may be passed as a parameter, but not used in the script")]
Param (
#If specifying the worksheet by name, the ExcelPackage object which contains the worksheet also needs to be passed.
[Parameter(ParameterSetName="Package",Mandatory=$true)]
@@ -138,7 +140,7 @@
process {
if ($null -eq $workSheet.Dimension) {Write-Warning "Can't format an empty worksheet."; return}
if ($Column -eq 0 ) {$Column = $endColumn + 1 }
$columnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1",""
$columnName = (New-Object 'OfficeOpenXml.ExcelCellAddress' @(1, $column)).Address -replace "1",""
Write-Verbose -Message "Updating Column $columnName"
#If there is a heading, insert it and use it as the name for a range (if we're creating one)
if ($PSBoundParameters.ContainsKey('Heading')) {

View File

@@ -33,6 +33,8 @@
[cmdletbinding()]
[Alias("Set-Row")]
[OutputType([OfficeOpenXml.ExcelRow],[String])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="Variables created for script block which may be passed as a parameter, but not used in the script")]
Param (
#An Excel package object - e.g. from Export-Excel -PassThru - requires a sheet name.
[Parameter(ParameterSetName="Package",Mandatory=$true)]
@@ -143,7 +145,7 @@
#Fill in the data
if ($PSBoundParameters.ContainsKey('Value')) {foreach ($column in ($StartColumn..$endColumn)) {
#We might want the column name in a script block
$columnName = [OfficeOpenXml.ExcelCellAddress]::new(1,$column).Address -replace "1",""
$columnName = (New-Object -TypeName OfficeOpenXml.ExcelCellAddress @(1,$column)).Address -replace "1",""
if ($Value -is [scriptblock] ) {
#re-create the script block otherwise variables from this function are out of scope.
$cellData = & ([scriptblock]::create( $Value ))
@@ -177,7 +179,7 @@
if ($PSBoundParameters.ContainsKey($p)) {$params[$p] = $PSBoundParameters[$p]}
}
if ($params.Count) {
$theRange = [OfficeOpenXml.ExcelAddress]::New($Row, $StartColumn, $Row, $endColumn)
$theRange = New-Object -TypeName OfficeOpenXml.ExcelAddress @($Row, $StartColumn, $Row, $endColumn)
Set-ExcelRange -WorkSheet $Worksheet -Range $theRange @params
}
#endregion

View File

@@ -9,6 +9,7 @@
Set-WorkSheetProtection -WorkSheet $planSheet -IsProtected -AllowAll -AllowInsertColumns:$false -AllowDeleteColumns:$false -UnLockAddress "A:N"
Turns on protection for the worksheet in $planSheet, checks all the allow boxes excel Insert and Delete columns and unlocks columns A-N
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')]
param (
#The worksheet where protection is to be applied.
[Parameter(Mandatory=$true)]

View File

@@ -32,6 +32,7 @@
#>
[cmdletbinding()]
[Alias("Set-Format")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',Justification='Does not change system state')]
Param (
#One or more row(s), Column(s) and/or block(s) of cells to format.
[Parameter(ValueFromPipeline = $true,Position=0)]

View File

@@ -1,3 +1,8 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Scope='Function', Target='Update*', Justification='Does not change system state')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Scope='Function', Target='Update*', Justification='Property would be incorrect')]
param()
Function Update-FirstObjectProperties {
<#
.SYNOPSIS
@@ -79,7 +84,7 @@ Function Update-FirstObjectProperties {
$Union = @()
$Input | ForEach-Object {
If ($Union.Count) {
$_ | Get-Member | Where {-not ($Union[0] | Get-Member $_.Name)} | ForEach-Object {
$_ | Get-Member | Where-Object {-not ($Union[0] | Get-Member $_.Name)} | ForEach-Object {
$Union[0] | Add-Member -MemberType NoteProperty -Name $_.Name -Value $Null
}
}

View File

@@ -328,7 +328,7 @@ Describe "Merge Multiple sheets" {
$ws.Cells[12,9 ].Value | Should be $ws.Cells[12,5].Value
$ws.Cells[12,10].Value | Should be $ws.Cells[12,6].Value
}
it "Creared Conditional formatting rules " {
it "Created Conditional formatting rules " {
$cf=$ws.ConditionalFormatting
$cf.Count | Should be 17
$cf[16].Address.Address | Should be 'B2:B1048576'

View File

@@ -91,9 +91,9 @@ Describe "Join Worksheet part 1" {
}
$path = "$env:TEMP\Test.xlsx"
Remove-item -Path $path -ErrorAction SilentlyContinue
IF ($PSVersionTable.PSVersion.Major -gt 5) {Write-warning -message "Part 2 Does not run on V6"; return}
#switched from WMI to CIM objects so test runs on V6
Describe "Join Worksheet part 2" {
Get-WmiObject -Class win32_logicaldisk |
Get-CimInstance -ClassName win32_logicaldisk |
Select-Object -Property DeviceId,VolumeName, Size,Freespace |
Export-Excel -Path $path -WorkSheetname Volumes -NumberFormat "0,000"
Get-NetAdapter |

View File

@@ -69,6 +69,8 @@
Only the unchanged rows are highlighted.
#>
[cmdletbinding(DefaultParameterSetName)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification="Write host used for sub-warning level message to operator which does not form output")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives when initializing variable in begin block")]
Param(
#First file to compare.
[parameter(Mandatory=$true,Position=0)]
@@ -219,11 +221,9 @@
}
elseif ($diff -and $FontColor) {Write-Warning -Message "To match rows to set changed cells, you must specify -Key and it must match one of the included properties." }
#if nothing was found write a message which wont be redirected
#if nothing was found write a message which will not be redirected
if (-not $diff) {Write-Host "Comparison of $Referencefile::$worksheet1 and $Differencefile::$WorkSheet2 returned no results." }
if ($Show) {
Start-Process -FilePath $Referencefile
if (-not $oneFile) { Start-Process -FilePath $Differencefile }

View File

@@ -1,3 +1,5 @@
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification="False positives")]
param()
class PSPlot {
hidden $path
hidden $pkg