2017-07-25 3 views
0

Ich wurde damit beauftragt, einen Teil des Logging-Prozesses auf einem SPLA-Server des Unternehmens zu automatisieren. Meine Aufgabe besteht darin, die alten Dateien zu datieren, zu archivieren und zu entfernen, und dann einen Bericht zu erstellen, der per E-Mail an die Abteilung gesendet wird. Diese Aufgabe soll am Ende jeder Woche ausgeführt werden.Zusätzliche Zeilen in einer Excel-Datei mit Powershell löschen?

Ich dachte Powershell wäre die beste Option, um diese Aufgabe abzuschließen. Dies ist das erste Mal, dass ich mit Powershell arbeite, also musste ich etwas lernen.

Meine Frage:

Ist es möglich, durch eine Excel-Arbeitsblatt Schleife und nicht verwendete Zeilen löschen Sie dieses Skript verwenden?

Mein Zustand wäre, wenn es zwei leere Zeilen -> eine Zeile löschen und halten

werde ich nehme Informationen aus dem Protokoll und die Aufteilung in eine CSV dann die CSV für die Formatierung in eine Excel konvertieren.

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 

Der folgende Code funktioniert durch das Programm auszuführen:

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

Es könnte einfacher sein, die überspringen CSV Schritt und analysieren Sie die Protokolldatei direkt in Excel. Hier ist ein [nützliches PS Excel-Modul] (https://blogs.technet.microsoft.com/heyscriptingguy/2015/11/25/introducing-the-powershell-excel-module-2/) – TheIncorrigible1

Antwort

0

Dies sollte relativ einfach sein, nach vorne

$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 
Verwandte Themen