【发布时间】:2020-12-16 14:51:46
【问题描述】:
我正在运行一个小脚本来比较一个文件中存在的内容与一个返回数组的命令的响应
$data = @('Zero','One','Two','Three')
$file = "C:\test.txt"
# Save the array to file
Set-Content $file (Out-String -InputObject $data)
#compair file to array
$IsIdentical = Compare-Object -ReferenceObject (get-content -Path $file) -DifferenceObject (Out-String -InputObject $data)
if($IsIdentical -eq $null)
{
Write-Output "Identical"
}
else
{
Write-Output "Not Identical"
}
我的输出为Not Identical
谁能解释一下为什么不一样!!!另外,我该如何解决这个问题?
【问题讨论】:
-
使用
-Stream开关Out-String防止输出末尾出现多余的空行。 -
您可能希望将参数
-syncWindow 0添加到Compare-Object调用。见PowerShell order sensitive Compare-Objects diff。 -
@zett42 感谢我尝试过的回复,仍然收到
Not Identical。 -
我的评论不能解决您的问题,但它显示了如何解决另一个问题。
Compare-Object默认以任意顺序匹配项目。所以@('Zero','One','Two','Three')将与@('One','Zero','Two','Three')比较为“相等”。通过添加-syncWindow 0,只有在 order 也相等时,数组才会比较相等。 -
@zett42 compare-object 与默认同步窗口对于大文件也可能非常慢。
标签: powershell string-comparison