从 PowerShell 中的多个文本文件中删除行

Delete lines from multiple textfiles in PowerShell

我正在尝试从多个文本文件中删除具有已定义内容的行。

它在核心中工作,但即使没有进行任何更改,它也会重写每个文件,如果您只是修改大约 3000 个登录脚本中的 50 个,这就不太酷了。
我什至做了一个 if 语句,但它似乎不起作用。

好的,这是我已有的:

#Here $varFind will be escaped from potential RegEx triggers.
$varFindEscaped = [regex]::Escape($varFind)

#Here the deletion happens.
foreach ($file in Get-ChildItem $varPath*$varEnding) {
    $contentBefore = Get-Content $file
    $contentAfter = Get-Content $file | Where-Object {$_ -notmatch $varFindEscaped}
    if ($contentBefore -ne $contentAfter) {Set-Content $file $contentAfter}
}

变量的含义:
$varPath 是登录脚本所在的路径。
$varEnding 是要修改的文件的文件结尾。
$varFind是触发删除行的字符串

非常感谢任何帮助。

问候
洛瓦分

无论如何您都必须阅读该文件,但对您的更改条件进行一些改进可能会有所帮助。

#Here the deletion happens.
foreach ($file in Get-ChildItem $varPath*$varEnding) {
    $data = (Get-Content $file)
    If($data -match $varFindEscaped){
        $data | Where-Object {$_ -notmatch $varFindEscaped} | Set-Content $file
    }
}

将文件读入$data。检查文件中是否存在模式 $varFindEscaped。如果是,则过滤掉那些匹配相同模式的。否则我们进入下一个文件。