代码之家  ›  专栏  ›  技术社区  ›  Rakha

仅当文件中不存在变量时才输出文件

  •  0
  • Rakha  · 技术社区  · 7 年前

    目标:仅当文本文件中不存在变量时,才将变量写入该文本文件。

    我在做什么:

    if (! (Get-Content "C:\historique.txt" | Where-Object {$_ -like $var})) {
        $var | Out-File -Encoding Ascii -FilePath "C:\historique.txt" -Append -Force
    }
    

    这是可行的,但这是最好/最快的方法吗?该文件不会得到真正的巨大,但我希望它是尽可能优化。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Theo    7 年前

    你可以使用 -notmatch 比较正则表达式,查看文件内容中是否没有所需的字符串 $var

    $file = 'C:\historique.txt'
    $var  = 'blah'
    if ((Get-Content -Path $file -Raw) -notmatch [regex]::Escape($var)) {
        Add-Content -Path $file -Value $var -Encoding Ascii -Force
    }
    
    推荐文章