2017-07-25 54 views
0

我的任務是自動完成公司擁有的SPLA服務器上的部分日誌記錄過程。我的任務是約會,存檔和刪除舊文件,然後轉到生成報告以通過電子郵件發送給部門。這項任務應該在每週結束時運行。使用powershell刪除excel文件中的額外行?

我認爲PowerShell是完成此任務的最佳選擇。這是我第一次使用PowerShell,所以我有一些學習要做。

我的問題:

是否有可能遍歷Excel工作表,並使用該腳本刪除未使用的行? >刪除一行,並堅持下去

我正在從日誌和分裂它的信息到CSV然後轉換CSV到Excel格式化 - 如果有兩個空行

我的狀態會。

Sample of the Excel spreadsheet, others vary in excess rows between information

Get-ChildItem C:\ScriptsDirectory1\*.log | foreach{ 

$input = Get-Content $_.FullName            #Initialize input 
$a = Get-Date                 #Save the current date (for if/else wrapper) 
#=============================================# 
#    File Name Changer    # 
#=============================================# 

$x = $_.LastWriteTime.ToShortDateString()          #Save a temp variable with the LastWriteTime and send it to a string 

$new_folder_name = Get-Date $x -Format yyyy.MM.dd        #Create a new folder that contains the string information 

$des_path = "C:\Archive\ArchivedLogs\$new_folder_name"       #Send the new folder to the archive directory 
#=============================================# 


$data = $input[1..($input.Length - 1)]           #Initialize Array and set it to the length of the input file. 
$maxLength = 0 


$objects = ForEach($record in $data) {           #Loop through each object within the array 

    $split = $record -split ": "            #Split objects within array at the ": " string 
    If($split.Length -gt $maxLength){ 
     $maxLength = $split.Length 
    } 

    $properties = @{} 

    For($i=0; $i -lt $split.Length; $i++) {          #Adds the split information to the strings array 
     $properties.Add([String]($i+1),$split[$i]) 
    } 

    New-Object -TypeName PSObject -Property $properties 
} 
$objects | format-table 

$headers = [String[]](1..$maxLength) 

$objects | 
Select-Object $headers | 

Export-Csv -NoTypeInformation -Path "C:\Archive\CSVReports\$new_folder_name.csv"#Export CSV path using the new folder name to prevent overwrite 

if (test-path $des_path){              #Test if the path exists, and fill the directory with the file to be archived 

    move-item $_.fullname $des_path 
    } else { 
    new-item -ItemType directory -Path $des_path 
    move-item $_.fullname $des_path 
    } 
} #End of Parser 

#===============================================================================# 
#======================================#========================================# 
#===============================================================================# 
#     File Archiver and Zipper (After Parse/CSV)     # 
#===============================================================================# 
#======================================#========================================# 
#===============================================================================# 
$files = Get-ChildItem C:\Archive\ArchivedLogs         #Fill the $files variable with the new files in the Archive directory 

#********************************# 
#Loop Through and Compress/Delete# 
#********************************# 
foreach ($file in $files) { 

    Write-Zip $file "C:\Archive\ArchivedLogs\$file.zip" -Level 9    #Write compressed file 

} #End of Archiver 
Remove-Item C:\Archive\ArchivedLogs\* -exclude *.zip -recurse     #Remove the un-needed files within the archive folder  
#Run the Formatting and Conversion script for the CSV-to-XLSX 
#C:\ScriptsDirectory1\Script\TestRunner1.ps1 #<---Can be Ran using a Invoke call 
#===============================================================================# 
#======================================#========================================# 
#===============================================================================# 
#       CSV to XLSX Format/Conversion      # 
#===============================================================================# 
#======================================#========================================# 
#===============================================================================# 
Get-ChildItem C:\Archive\CSVReports | foreach{ 
$excel_file_path = $_.FullName             #Create the file path variable to initialize for formating 
$Excel = New-Object -ComObject Excel.Application        #Start a new excel application 

$Excel.Visible = $True 
$Excel.DisplayAlerts=$False 
$Excel_Workbook = $Excel.Workbooks.Open($excel_file_path)      #Create workbook variable and open a workbook in the path 
$FileName = $_.BaseName               #Save the base file name of the current value 
$Excel.ActiveSheet.ListObjects.add(1,$Excel_Workbook.ActiveSheet.UsedRange,0,1) 
$Excel_Workbook.ActiveSheet.UsedRange.EntireColumn.AutoFit() 

$SPLA1wksht = $Excel_Workbook.Worksheets.Item(1)        #Create the new Sheet (SPLA1wksht) 
#*******************************************************# 
#     Formating for Title Cell    # 
#*******************************************************# 
$SPLA1wksht.Name = 'SPLA Info Report'           #Change worksheet name 
$SPLA1wksht.Cells.Item(1,1) = $FileName           #Title (Date of log) in cell A1 
$SPLA1wksht.Cells.Item(1,2) = 'SPLA Weekly Report'        #Title for all Excel reports 
$SPLA1wksht.Cells.Item(1.2).Font.Size = 18 
$SPLA1wksht.Cells.Item(1.2).Font.Bold=$True 
$SPLA1wksht.Cells.Item(1.2).Font.Name="Cambria" 
$SPLA1wksht.Cells.Item(1.2).Font.ThemeFont = 1 
$SPLA1wksht.Cells.Item(1.2).Font.ThemeColor = 5 
$SPLA1wksht.Cells.Item(1.2).Font.Color = 8210719 
#*******************************************************# 

#************************************# 
#  Adjust and Merge Cell B1 # 
#************************************# 
$range = $SPLA1wksht.Range("b1","h2") 
$range.Style = 'Title' 

$range = $SPLA1wksht.Range("b1","g2") 

$range.VerticalAlignment = -4108            #Center align vertically (Value -4108 is center) 
#************************************# 

#***********************************************************************# 
#      Horizontal Centering for all cells    # 
#***********************************************************************# 
$ColumnRange = $SPLA1wksht.Range("a1","a500").horizontalAlignment =-4108  #Center all cells in this range as -4108 
$ColumnRange = $SPLA1wksht.Range("b1","b500").horizontalAlignment =-4108 

#**********************************************# 
#    Delete Blank Rows Inneffective- Logs that have different 
#data end up with a different amount of rows and offsets this deletion   
#        # This method deletes the first row then 
#moves onto 
#**********************************************#        # the next-in-line blank lines and deletes the one 
#$SPLA1wksht.Cells.Item(2,1).EntireRow.Delete() #        # line until the blank spots are in perfect format 
               # 
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() # 
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() # 
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() # 
#$SPLA1wksht.Cells.Item(4,1).EntireRow.Delete() # 
               # 
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(19,1).EntireRow.Delete()# 
               # 
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(25,1).EntireRow.Delete()# 
               # 
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()# 
#$SPLA1wksht.Cells.Item(33,1).EntireRow.Delete()# 
#**********************************************# 

#*****************************************************************# 
#    Final Export as a CSV-to-XLSX file    # 
#*****************************************************************# 
$Excel_Workbook.SaveAs("C:\Archive\ExcelReports\$FileName.xlsx",51)    #Save the file in the proper location 
$Excel_Workbook.Saved = $True 
$Excel.Quit() 
# Find a way to optimize this process 

#Potential optimization places: 
# 1.) Don't open and close excel file and instead just write changes and save 
# 2.) Change way empty rows are formatted instead of seperate calls each time 
} #End of Format/Converter 
#******End******# 

#---------------#--#--------------# 
#---------------------------------# 
# What to Add to the Script # 
#---------------------------------# 
#---------------#--#--------------# 
# -[/] <-Complete -[] <- Incomplete 
# -[] Archive or delete CSV Files 
# -[] Add a If/Else statement that checks if files are >7 days old 
# -[] Compile a weekender report that indicates any SPLA programs changed to keep compliance 
# -[] Filter for only SPLA files (Need a list) 
# -[] Loop through CSV/Excel file and delete empty rows 

下面的代碼工作通過程序運行:

for($i = 350 ; $i -ge 0 ; $i--) { 
    If ($SPLA1wksht.Cells.Item($i, 1).Text-eq "") { 
     $Range = $SPLA1wksht.Cells.Item($i, 1).EntireRow 
     [void]$Range.Delete() 
     echo $i 
    } 
    If ($SPLA1wksht.Cells.Item($i, 2).Text-eq "") { 
     $Range = $SPLA1wksht.Cells.Item($i, 2).EntireRow 
     [void]$Range.Delete() 
     echo $i 
    } 
    If($i -eq 2){ break;} 
} 
+1

可能更容易跳過CSV步驟並將日誌文件直接解析到Excel中。這是一個[有用的PS Excel模塊](https://blogs.technet.microsoft.com/heyscriptingguy/2015/11/25/introducing-the-powershell-excel-module-2/) – TheIncorrigible1

回答

0

這應該是相對簡單的

$file = C:\path\to\file.csv 
$csv = Import-Csv $file 

foreach($row in $csv) { 
    # logic to delete row 
    # $csv is an array, so you can could make the row = null to delete it 
} 
# spit out updated excel sheet 
Export-Csv | $csv -NoTypeInformation