Reputation: 31
I am trying to loop through a file and remove lines that are not needed. The rows in the file have a unique number that does not change. What I have so far does not remove the line in the foreach loop but separately it does.
$FSEFiles=get-childitem E:\FSE*.txt
foreach ($file in $FSEFiles)
{
try
{
(Get-Content $file.PSPath) |
Foreach-Object { Where-Object { $_ -notmatch "15987@" } } |
Foreach-Object { Where-Object { $_ -notmatch "16422@" } } |
#Foreach-Object {Where-Object { $_ -notmatch "17526@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17527@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17528@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17530@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17531@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17532@"}} |
Set-Content $file.PSPath
write-host $file updated
}
catch
{
write-host Error editing $file
}
}
Did I miss something that will allow this loop to work on each line?
Upvotes: 3
Views: 1135
Reputation: 46710
Since you are already using regex lets merge all these requirements into one nice regex string
$regex = "(15987@|16422@|1752[6-8]@|1753[0-2]@)"
$data = Get-Content $file.PSPath
$data | Where-Object{$_ -notmatch $regex} | Set-Content $file.PSPath
Perhaps something like that would stream line it. Not really tested but should work. What you have might have worked in place but something seems malformed with the combination of foreach
and where
( hence the question ) but it would be redundant to try and address that I would think.
Upvotes: 3