比较两个文本文件并输出Powershell中的差异



所以我是Powershell脚本世界的新手,我正在尝试将文本文件中的IP列表与IP列表数据库进行比较。如果(数据库(文件中不存在来自(文件(的IP,请将其放在一个新文件中,我们称之为compared.txt。当我尝试运行脚本时,没有得到任何结果。我在这里错过了什么?

$file = Get-Content "C:UserszackDesktopfile.txt"
$database = Get-Content "C:UserszackDesktopdatabase.txt"
foreach($line1 in $file){
$check = 0
foreach($line2 in $database)
{
if($line1 != $line2)
{
$check = 1
}
else
{
$check = 0
break
}
}
if ($check == 1 ) 
{
$line2 | Out-File "C:UserszackDesktopcompared.txt"
}
}

C#不同,PowerShell比较运算符的使用存在问题,等式和不等式分别为-eq-ne,并且由于PowerShell是不区分大小写的语言,因此还有-ceq-cne

代码的逻辑也有问题,一个简单的工作版本是:

$database = Get-Content "C:UserszackDesktopdatabase.txt"
# iterate each line in `file.txt`
$result = foreach($line1 in Get-Content "C:UserszackDesktopfile.txt") {
# iterate each line in `database.txt`
# this happens on each iteration of the outer loop
$check = foreach($line2 in $database) {
# if this line of `file.txt` is the same as this line of `database.txt`
if($line1 -eq $line2) {
# we don't need to keep checking, output this boolean
$true
# and break the inner loop
break
}
}
# if above condition was NOT true
if(-not $check) {
# output this line, can be `$line1` or `$line2` (same thing here)
$line1
}
}
$result | Set-Content pathtocomparisonresult.txt

然而,还有更简单的方法可以实现相同的结果:

  • 使用包含运算符:
$database = Get-Content "C:UserszackDesktopdatabase.txt"
$result   = foreach($line1 in Get-Content "C:UserszackDesktopfile.txt") {
if($line1 -notin $database) {
$line1
}
}
$result | Set-Content pathtocomparisonresult.txt
  • 使用Where-Object
$database = Get-Content "C:UserszackDesktopdatabase.txt"
Get-Content "C:UserszackDesktopfile.txt" | Where-Object { $_ -notin $database } |
Set-Content pathtocomparisonresult.txt
  • 使用HashSet<T>及其ExceptWith方法(注意,这也将消除file.txt中的重复项(:
$file = [System.Collections.Generic.HashSet[string]]@(
Get-Content "C:UserszackDesktopfile.txt"
)
$database = [string[]]@(Get-Content "C:UserszackDesktopdatabase.txt")
$file.ExceptWith($database)
$file | Set-Content pathtocomparisonresult.txt

最新更新