Search code examples
powershell

PowerShell ForEach Loop - delete current line


I have a simple ForEach loop

ForEach ($line in Get-Content documents.txt) {

... code ...

}

and I would like to remove that line from the original file once my code has been processed.

What would be the best approach to achieve this?

Thanks in advance.


Solution

  • IF your question is about doing something with each line in a text file and afterwards empty that file, you can do:

    $filePath = 'D:\SomeFolder\documents.txt'
    foreach ($line in (Get-Content -Path $filePath )) {
        # here you process the line
        # ... code ...
    }
    # you have processed all lines, so empty the original file
    Clear-Content -Path $filePath
    

    IF however you mean to do something with each line that matches a condition and keep the rest, do:

    $filePath = 'D:\SomeFolder\documents.txt'
    $newContent = foreach ($line in (Get-Content -Path $filePath )) {
        # here you process the line
        # dummy code:
        if ($line -like '*anything*') { 
            # do what you need to do with that line 
            # don't output this line because you're finished with processing it
        }
        else { $line }  # output the original line
    }
    
    # now you have an array of lines you did not process and the rest is gone. Save the new lines
    $newContent | Set-Content -Path $filePath
    

    These are just examples. If you can tell us more about the documents.txt file (is it huge or small) and what you are intending to do with the 'processing', there are lots of different other ways of dealing with this.