首页 > 解决方案 > 将文件内容与 Powershell 中的字符串进行比较

问题描述

我正在尝试将文本文件的内容与字符串进行比较。听起来很简单,但没有运气!

$mystring = @'
hello
goodbye
'@

set-content c:\temp\file.txt $mystring

if (Test-Path "c:\temp\file.txt") {
    $myfile = Get-Content "c:\temp\file.txt" -raw
    if ($myfile -eq $mystring) {
        write-host 'File same'
    }
    else {
        write-host 'File different'
    }
}
else {
    write-host 'No file'
}

Write-Host $mystring.Length
Write-Host $myfile.Length

输出

File different
14
16

两个字符串的长度不同,当您打开文件时,底部有一个新行,我假设长度中额外的 2 个字符来自该行。

我错过了什么?

标签: powershell

解决方案


-NoNewlineset-content 命令中追加

所以你的整行将是

Set-Content "c:\temp\file.txt" $mystring -NoNewline

推荐阅读