Powershell - Delete line from text file if it contains certain string

Tan Huynh 241 Reputation points
2020-12-11T15:14:07.347+00:00

Hello everyone,

I have script below which will delete a line that contains a certain string which works fine but it is extremely slow since file2 is big (over 50MB). To increase performance, how do I modify it to do:

  1. Delete only one line on first match (don't know if this will improve performance)
  2. file2 get's saved on every run which may cause performance issue?

Other ideas to improve performance will be greatly appreciated. Thank you.

foreach ($string in (Get-Content c:\strings.txt))

{

(Get-Content 'c:\file2.csv') -notmatch $string | Set-Content 'c:\file2.csv'

}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,360 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tan Huynh 241 Reputation points
    2020-12-11T22:04:09.963+00:00

    I ended up using this script from another forum. Thanks.

    $Path = 'C:\file2.csv’
    $Content = [System.IO.File]::ReadAllLines($Path)
    foreach ($string in (Get-Content c:\strings.txt))
    {
    $Content = $Content -replace $string,''
    }
    $Content | Set-Content -Path $Path

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful