我正在尝试编写一个从 DataTable 中过滤掉重复条目的函数。我的代码工作正常,但前提是行:3-4 不在注释中。我尝试将 $tbl1 变量的默认范围更改为全局,但没有帮助。
我在做什么?代码如下。
Function RemoveDuplicates
{
#$tbl1 | export-csv ".\tmp.csv" #Code works perfectly when you uncomment these two lines.
#$tbl1 = import-csv ".\tmp.csv" #
$t_tbl = $tbl1 | Sort-Object -Property Prop3 -Unique
$duplicates = Compare-Object -ReferenceObject $tbl1 -DifferenceObject $t_tbl -Property Prop3
#$duplicates
write-host "tbl1 count: $($tbl1.Rows.Count)"
write-host "t_tbl count: $($t_tbl.Count)"
write-host "duplicates count: $(@($duplicates).Count)"
write-host "Found $($tbl1.Rows.Count) entries. $($t_tbl.Count) entries have unique Prop3. Duplicates: $(@($duplicates).count)"
}
$tbl1 = New-Object System.Data.DataTable
$col1 = New-Object System.Data.DataColumn Prop1,([string])
$col2 = New-Object System.Data.DataColumn Prop2,([string])
$col3 = New-Object System.Data.DataColumn Prop3,([string])
$tbl1.Columns.Add($col1)
$tbl1.Columns.Add($col2)
$tbl1.Columns.Add($col3)
$row = $tbl1.NewRow()
$row.Prop1 = "Jane"
$row.Prop2 = "Doe"
$row.Prop3 = "jane.doe@domain.local"
$tbl1.Rows.Add($row)
$row = $tbl1.NewRow()
$row.Prop1 = "Jack"
$row.Prop2 = "Awesome"
$row.Prop3 = "jane.doe@domain.local"
$tbl1.Rows.Add($row)
$row = $tbl1.NewRow()
$row.Prop1 = "Julia"
$row.Prop2 = "Whatever"
$row.Prop3 = "test@domain.local"
$tbl1.Rows.Add($row)
$row = $tbl1.NewRow()
$row.Prop1 = "Mr"
$row.Prop2 = "ScriptGuy!"
$row.Prop3 = "scriptguy@domain.local"
$tbl1.Rows.Add($row)
$row = $tbl1.NewRow()
$row.Prop1 = "Mrs"
$row.Prop2 = "ScriptLady!"
$row.Prop3 = "scriptlady@domain.local"
$tbl1.Rows.Add($row)
RemoveDuplicates
谢谢