gpt4 book ai didi

powershell - 比较6个对象的内容并删除不匹配的对象

转载 作者:行者123 更新时间:2023-12-03 00:49:51 26 4
gpt4 key购买 nike

我有一些动态创建的6个文件(因此,我不知道其内容)。我需要比较这6个文件(确切地说是将一个文件与其他5个文件进行比较),然后查看文件1中的所有内容与其他文件5中的内容是否匹配。匹配的内容应保存,其他内容应删除。

我编码如下,但是正在删除所有内容(也匹配)。

$lines = Get-Content "C:\snaps.txt"
$check1 = Get-Content "C:\Previous_day_latest.txt"
$check2 = Get-Content "C:\this_week_saved_snaps.txt"
$check3 = Get-Content "C:\all_week_latest_snapshots.txt"
$check4 = Get-Content "C:\each_month_latest.txt"
$check5 = Get-Content "C:\exclusions.txt"
foreach($l in $lines)
{
if(($l -notmatch $check1) -and ($l -notmatch $check2) -and ($l -notmatch $check3) -and ($l -notmatch $check4))
{
Remove-Item -Path "C:\$l.txt"
}else
{
#nothing
}
}
foreach($ch in $check5)
{
Remove-Item -Path "C:\$ch.txt"
}

6个文件的内容如下所示:

$行
testinstance-01-07-15-08-00
testinstance-10-07-15-23-00
testinstance-13-02-15-13-00
testinstance-15-06-15-23-00
testinstance-19-01-15-23-00
testinstance-23-05-15-20-00
testinstance-27-03-15-23-00
testinstance-28-02-15-23-00
testinstance-29-07-15-08-00
testinstance-30-04-15-23-00
testinstance-30-06-15-23-00
testinstance-31-01-15-23-00
testinstance-31-12-14-23-00

$ check1
testinstance-29-07-15-08-00

$ check2
testinstance-23-05-15-20-00
testinstance-27-03-15-23-00

$ check3
testinstance-01-07-15-23-00
testinstance-13-02-15-13-00
testinstance-19-01-15-23-00

$ check4
testinstance-28-02-15-23-00
testinstance-30-04-15-23-00
testinstance-30-06-15-23-00
testinstance-31-01-15-23-00

$ check5
testinstance-31-12-14-23-00

我已经了解了比较对象。但是不确定在我的情况下如何实现,因为所有5个文件的内容都将不同,并且所有这些内容都应保存为删除状态。有人可以指导我实现我所说的吗?任何帮助将非常感激。

最佳答案

我将创建文件的array进行检查,以便您可以简单地添加新文件而无需修改脚本的其他部分。

我使用where cmdlet,该命令使用-in条件过滤引用文件中的所有行,并最终覆盖文件:

$referenceFile = 'C:\snaps.txt'

$compareFiles = @(
'C:\Previous_day_latest.txt',
'C:\this_week_saved_snaps.txt',
'C:\all_week_latest_snapshots.txt',
'C:\each_month_latest.txt',
'C:\exclusions.txt'
)

# get the content of the reference file
$referenceContent = (gc $referenceFile)

foreach ($file in $compareFiles)
{
# get the content of the file to check
$content = (gc $file)

# filter all contents from the file to check which are in the reference file and save it
$content | where { $_ -in $referenceContent } | sc $file
}

关于powershell - 比较6个对象的内容并删除不匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31741024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com