比较if语句Powershell中的对象

Ale*_*zie 5 string powershell if-statement powershell-4.0

我正在尝试比较两个文件,如果它们的内容匹配,我希望它在Powershell 4.0中的if语句中执行任务

这是我所拥有的要点:

$old = Get-Content .\Old.txt
$new = Get-Content .\New.txt
if ($old.Equals($new)) {
 Write-Host "They are the same"
}
Run Code Online (Sandbox Code Playgroud)

文件是相同的,但它总是评估为false.我究竟做错了什么?有没有更好的方法来解决这个问题?

Kei*_*ill 12

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"
}
Run Code Online (Sandbox Code Playgroud)

注意-ceq这里使用字符串进行区分大小写的比较.-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"
}
Run Code Online (Sandbox Code Playgroud)