仅当文件中不存在变量时才输出文件
Out-File only if the variable doesn't exist in the file
目标:仅当文本文件中不存在变量时才将变量写入该文本文件。
我在做什么:
if (! (Get-Content "C:\historique.txt" | Where-Object {$_ -like $var})) {
$var | Out-File -Encoding Ascii -FilePath "C:\historique.txt" -Append -Force
}
"If the $var is NOT found in the file, Out-File..."
它有效,但这是最好/最快的方法吗?该文件不会变得很大,但我希望它尽可能优化。
您可以使用 -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
}
目标:仅当文本文件中不存在变量时才将变量写入该文本文件。
我在做什么:
if (! (Get-Content "C:\historique.txt" | Where-Object {$_ -like $var})) {
$var | Out-File -Encoding Ascii -FilePath "C:\historique.txt" -Append -Force
}
"If the $var is NOT found in the file, Out-File..."
它有效,但这是最好/最快的方法吗?该文件不会变得很大,但我希望它尽可能优化。
您可以使用 -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
}