目标:仅当文本文件中不存在变量时,才将变量写入该文本文件。
我在做什么:
if (! (Get-Content "C:\historique.txt" | Where-Object {$_ -like $var})) { $var | Out-File -Encoding Ascii -FilePath "C:\historique.txt" -Append -Force }
这是可行的,但这是最好/最快的方法吗?该文件不会得到真正的巨大,但我希望它是尽可能优化。
你可以使用 -notmatch 比较正则表达式,查看文件内容中是否没有所需的字符串 $var
-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 }