2016-02-05 155 views
0

我想从多个文本文件中删除具有定义内容的行。从PowerShell中的多个文本文件中删除行

它在核心中工作,但即使没有进行任何更改,它也会重写每个文件,如果您只是从大约3000个logonscripts中修改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是其中logonscripts是路径。
$ varEnding是要修改的文件的文件结尾。
$ varFind是触发删除行的字符串。

任何帮助将不胜感激。

问候
LOWA美分

回答

0

你必须阅读文件,而不管,但你的变化情况有所改善可能会有帮助。

#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模式。如果它是筛选出那些匹配相同的模式。否则,我们转到下一个文件。

+0

嗨马特你的代码就像一个魅力!非常感谢你! –