我正在尝试比较两个文件,如果它们的内容匹配,我希望它在 Powershell 4.0 的 if 语句中执行任务
这是我所拥有的要点:
$old = Get-Content .\Old.txt
$new = Get-Content .\New.txt
if ($old.Equals($new)) {
Write-Host "They are the same"
}
这些文件是相同的,但它总是评估为假。我究竟做错了什么?有没有更好的方法来解决这个问题?
我正在尝试比较两个文件,如果它们的内容匹配,我希望它在 Powershell 4.0 的 if 语句中执行任务
这是我所拥有的要点:
$old = Get-Content .\Old.txt
$new = Get-Content .\New.txt
if ($old.Equals($new)) {
Write-Host "They are the same"
}
这些文件是相同的,但它总是评估为假。我究竟做错了什么?有没有更好的方法来解决这个问题?
Get-Content
返回一个字符串数组。在数组上的 PowerShell(和 .NET).Equals()
中进行参考比较,即这是否是完全相同的数组实例。如果文件不是太大,一个简单的方法就是将文件内容作为字符串读取,例如:
$old = Get-Content .\Old.txt -raw
$new = Get-Content .\Newt.txt -raw
if ($old -ceq $new) {
Write-Host "They are the same"
}
请注意使用-ceq
here 在字符串之间进行区分大小写的比较。-eq
进行不区分大小写的比较。如果文件很大,则使用新的 Get-FileHash 命令,例如:
$old = Get-FileHash .\Old.txt
$new = Get-FileHash .\New.txt
if ($old.hash -eq $new.hash) {
Write-Host "They are the same"
}