如何使用powershell比较2个文本文件

如何使用powershell比较2个文本文件,powershell,Powershell,我想能够比较两个文本文件的内容,看看这些文件的内容是否相同。如果这两个文件的内容不同,我需要此powershell脚本向我发送一封电子邮件,其中列出了与这两个文件的差异。这是我的密码: $fromaddress = "noreply@xy.com" $toaddress = "me@xy.com " $Subject = "Comparing 2 text files" $login = "abc" $password = "12345" | Convertto-SecureString -As

我想能够比较两个文本文件的内容,看看这些文件的内容是否相同。如果这两个文件的内容不同,我需要此powershell脚本向我发送一封电子邮件,其中列出了与这两个文件的差异。这是我的密码:

$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中的所有内容。任何人知道为什么这对我不起作用吗?

要比较两个文件并确定它们是否相同,请使用文件哈希:

$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
}

你的初稿几乎是对的。您只需要添加-IncludeEqual

见下文。文本文件1和2只是“你好”,文本文件3是“你好”


编辑以展示如何使用IncludeEqual

这将扫描两个文本文件的差异,并将其传输到第三个文件

$File1 = "C:\Scripts\Txt1.txt"

$File2 = "C:\Scripts\Txt2.txt"

$Location = "C:\Scripts\Txt3.txt"

compare-object (get-content $File1) (get-content $File2) | format-list | Out-File $Location

输出:

获取每个文件的哈希值,并对其进行比较。使用
Get FileHash
@EBGreen谢谢您的回复,您能澄清一下Get FileHash在代码中的位置吗?你能提供一个例子吗?我建议你先打开一个powershell提示符,然后键入
Get-Help-Get-FileHash-Detail
。话虽如此,我发现您对电子邮件中的内容也有疑问。您已将邮件正文设置为
$body
,但我看不到您在代码中的任何地方定义了什么是
$body
。@EBGreen发送电子邮件的$body部分不是一个大问题。我只是注意到上面粘贴的代码中没有包含$body。问题是,我需要这封电子邮件包含两个文件之间的差异附件。在这种情况下,我从文件1获取所有信息。在这种情况下,您如何创建
$attach
?如果您不显示导致问题的代码,则很难帮助您解决问题。
-IncludeEqual
如何解决未显示差异的问题?更重要的是,
Compare Object
默认情况下会忽略大小写差异,散列不能。小窗口
Txt3.txt
不显示当前侧指示器
=>
$File1 = "C:\Scripts\Txt1.txt"

$File2 = "C:\Scripts\Txt2.txt"

$Location = "C:\Scripts\Txt3.txt"

compare-object (get-content $File1) (get-content $File2) | format-list | Out-File $Location