I need to prepare s Powershell script to check my NSG rules design sheet and Skip rows that have yellow cells, gray cells or blank cells. I have prepared below script but it is not working as expected. Can someone please help me to fix this script.
Powershell script:
# Load the EPPlus library
Add-Type -Path "/home/lokesh/EPPlus.dll" # Replace with the path to your EPPlus.dll file
# Create an Excel package object
$excelPackage = New-Object OfficeOpenXml.ExcelPackage
# Load the Excel file
$filePath = "/home/lokesh/NSG_Rules.xlsx"
$excelPackage = [OfficeOpenXml.ExcelPackage]::Load($filePath)
# Get the first worksheet from the Excel package
$worksheet = $excelPackage.Workbook.Worksheets[0] # Change the index if needed
# Define a function to check cell color
function IsYellow($cell) {
return ($cell.Style.Fill.BackgroundColor.Rgb -eq "FFFFFF00") # Yellow color code
}
# Skip rows with yellow, gray, or blank cells
$rowsToKeep = @()
foreach ($row in $worksheet.Cells.Rows) {
$skipRow = $false
foreach ($cell in $row.Cells) {
if (IsYellow($cell) -or $cell.Style.Fill.BackgroundColor.Rgb -eq "FFA9A9A9" -or -not $cell.Value) {
$skipRow = $true
break
}
}
if (-not $skipRow) {
$rowsToKeep += $row
}
}
The solution below:
addresses your question as asked, based on use of the current version (v7) of the EPPlus .NET library alone.
Note that EPPlus versions v5 and above require a paid license for commercial use.
Direct use of this library is not very PowerShell-friendly; the
ImportExcelPowerShell module - which actually builds on EPPlus - albeit on a locked-in v4.x version due to the v5+ license requirements - is usually the better choice.It:
collects the (data) rows of interest as
[OfficeOpenXml.ExcelRangeRow]instances in an output array for further processing; the cells of each such row can be enumerated via the.Rangeproperty, and each enumerated cell has a.Valueproperty.does not create PowerShell friendly
[pscustomobject]instances, with properties named for the header cells, the way thatImport-Excelfrom theImportExceldoes.does not attempt to update the spreadsheet itself, i.e. it doesn't remove the rows you want to skip (omit).
The other answer shows an
ImportExcel-based solution that performs these tasks.