【问题标题】:Compare file contents with string in Powershell将文件内容与 Powershell 中的字符串进行比较
【发布时间】:2019-08-05 10:14:37
【问题描述】:

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

$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


【解决方案1】:

set-content 命令中追加-NoNewline

所以你的整行将是

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

【讨论】:

    【解决方案2】:

    您可以在比较之前使用String.Trim() 删除尾随换行符:

    $myfile = (Get-Content "c:\temp\file.txt" -Raw).Trim()
    

    【讨论】:

    • 额外的换行符仍会在文件中,这可能不是预期的,因为它不在原始字符串中。
    【解决方案3】:

    可能的解决方案:

    添加参数-NoNewline

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

    可能重复:

    Set-Content appends a newline (line break, CRLF) at the end of my file

    解释:

    https://blogs.msdn.microsoft.com/jmanning/2007/05/23/powershell-gotcha-of-the-day-set-content-adds-newlines-by-default/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2017-03-28
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      相关资源
      最近更新 更多