我希望能够比较2个文本文件的内容,看看这些文件的内容是否相同。如果2个文件的内容不同,我需要这个powershell脚本向我发送一封电子邮件,其中包含2个文件的差异列表。这是我的代码:
$fromaddress = "noreply@xy.com"
$toaddress = "me@xy.com "
$Subject = "Comparing 2 text files"
$login = "abc"
$password = "12345" | Convertto-SecureString -AsPlainText -Force
$smtpserver = "smtp.office.com"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$message.Priority = [System.Net.Mail.MailPriority]::High
$smtp = new-object Net.Mail.SmtpClient($smtpserver, 587)
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($login, $password);
IF (Compare-Object -ReferenceObject (Get-Content $dir\file1.txt) -DifferenceObject (Get-Content $dir\file2.txt)){
Write-Output "The files are different "
$smtp.Send($message);
}
Else {
Write-Output "The files are not different"
}
我查看了建议使用Compare-Object
cmdlet的不同在线资源,但它似乎并不适用于我的情况。我的代码的问题是,它从file1返回所有内容。谁知道为什么这对我不起作用?
答案 0 :(得分:1)
要比较两个文件并确定它们是否相同,请使用文件哈希:
$hash1 = Get-FileHash $dir\file1.txt
$hash2 = Get-FileHash $dir\file2.txt
if($hash1 -eq $hash2){
'They are the same'
}else{
'They are NOT the same
}
答案 1 :(得分:0)
这会扫描2个文本文件中的差异并将其传递给第三个文件
$ awk ' {
n=split($0,a,FS,seps) # split record to a, preserve separators to seps, keep n
sub(/D/,"& ",a[5]) # replace first D with D space (not an add :)
for(i=1;i<=n;i++) # iterate all a
b=b a[i] seps[i] # gather to buffer b
print b; b="" # output and clear b
}' file
ATOM 12107 N CYS D 1742 -42.369 73.203 -44.599 1.00224.20 C N
答案 2 :(得分:-1)
你的初始脚本几乎是正确的。你只需要添加-IncludeEqual
见下文。文本文件1&amp; 2只是“喜欢那里”。文本文件3是“hi there2”
{str.replace(/ /g, '\u00a0').replace(/(?:\r\n|\r|\n)/g, '\u000a')}
编辑以展示如何使用IncludeEqual