string 比较一个 if 语句 Powershell 中的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20056628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:10:41  来源:igfitidea点击:

Compare objects in an if statement Powershell

stringpowershellif-statementpowershell-4.0

提问by Alex McKenzie

I'm trying to compare two files and if their content matches I want it to preform the tasks in the if statement in Powershell 4.0

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

Here is the gist of what I have:

这是我所拥有的要点:

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

The files are the same, but it always evaluates to false. What am I doing wrong? Is there a better way to go about this?

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

回答by Keith Hill

Get-Contentreturns an array of strings. In PowerShell (and .NET) .Equals()on an array is doing a reference comparison i.e. is this the same exact array instance. An easy way to do what you want if the files aren't too large is to read the file contents as a string e.g.:

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

Note the use of -ceqhere to do a case-sensitive comparison between strings. -eqdoes a case-insensitive compare. If the files are large then use the new Get-FileHash command e.g.:

请注意使用-ceqhere 在字符串之间进行区分大小写的比较。-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"
}