使用powershell脚本删除excel(.xls)中的重复行

时间:2012-08-16 09:23:26

标签: excel powershell duplicate-removal

我遇到了脚本问题。我需要删除XLS文件中的所有重复行。 这是我的剧本:

sdsfsdf
$out_fcalias = "D:\scripts\SAN\Out_fcAlias.txt"
$out_flogi = "D:\scripts\SAN\Out_flogi.txt" 
$out_zone = "D:\scripts\SAN\Out_zone.txt"
$out_zoneact = "D:\scripts\SAN\Out_zoneactive.txt"
$Final_Report= "D:\Scripts\SAN\Report_test.xls"

# Params
$i = "" 
$tmp_splitArray = ""
$tmp_SwitchName = ""
$tmp_FabricName = ""
$tmp_ZoneName = ""
$tmp_Fcid = ""
$tmp_WWNName = ""
$tmp_Output = ""

# create xls
$XLS = new-object -comobject excel.application 
$XLS.Visible = $True 
$XLS_File = $XLS.Workbooks.Add() 
$XLS_Sheet = $XLS_File.Worksheets.Item(1) 
$XLS_Sheet.Name = "Report"
$XLS_Sheet.Cells.Item(1,1) = "Fabric" 
$XLS_Sheet.Cells.Item(1,2) = "Zone" 
$XLS_Sheet.Cells.Item(1,3) = "Fcid" 
$XLS_Sheet.Cells.Item(1,4) = "WWN" 
$XLS_Sheet.Cells.Item(1,5) = "Switch"
$XLS_Sheet.Cells.Item(1,6) = "FCID"
$XLS_Sheet.Cells.Item(1,7) = "Port Name"
$XLS_Sheet.Cells.Item(1,8) = "Node Name"
$XLS_Sheet.Cells.Item(1,9) = "Alias"
$XLS_LineCounter = 2 

$a = get-content $out_zoneact

foreach ( $i in $a)
    { 
    if ($i -match "Fabric") { $tmp_FabricName = $i}
    if ($i -match "zone name") 
        { 
        $tmp_splitArray = [regex]::split($i, " ") 
        $tmp_ZoneName = $tmp_splitArray[2]
        }
    if ($i -match " fcid ") 
        { 
        $tmp_splitArray = [regex]::split($i, " ")
        $tmp_Fcid = $tmp_splitArray[2]
    }
if ($i -match "pwwn")
    {
    $tmp_splitArray = [regex]::split($i, " ")
    $tmp_WWNName = $tmp_splitArray[4]
    $XLS_Sheet.cells.item($XLS_LineCounter,1) = $tmp_FabricName
    $XLS_Sheet.cells.item($XLS_LineCounter,2) = $tmp_ZoneName
    $XLS_Sheet.cells.item($XLS_LineCounter,3) = $tmp_Fcid
    $XLS_Sheet.cells.item($XLS_LineCounter,4) = $tmp_WWNName.Substring(0,$tmp_WWNName.Length-1)
    $XLS_LineCounter = $XLS_LineCounter + 1
    }
}
#autofit
$objRange = $XLS_Sheet.UsedRange 
[void] $objRange.EntireColumn.Autofit() 


$XLS_File.SaveAs($Final_Report) 
$XLS_File.Close()
$XLS.Quit()    

所以我有很多重复的行,我需要以编程方式删除它们,所以我可以把它放在我的脚本中。

2 个答案:

答案 0 :(得分:1)

# autofit之后,插入

$XLS_Sheet.UsedRange.RemoveDuplicates()

应按照MSDN

的规定运作

答案 1 :(得分:0)

很抱歉更新一个旧线程,但是我花了一些时间弄清楚了为什么它不起作用。关于Mat M的解决方案,我发现您需要指定数组中的列索引作为参数。

$cols = 1,2,3,4,5,6,7,8,9    
$XLS_Sheet.UsedRange.RemoveDuplicates($cols)