0

I have file with the content of

123
234
345

I am using a foreach loop to read each line of the file.

I have a requirement like: I would like to remove each line of the file inside the foreach loop.

Is there anyway to remove line of the file inside foreach loop?

Here's what I've tried:

$source1 = "Y:\New Documents\test.txt"
foreach ($line in Get-Content $source1) {
    $find = $line
    (Get-Content $source1).replace($find,"") |
        Set-Content $source1
}

I am able to clear the content of file and I don't know how to make file with zero size.

15
  • And removing each line will render you an empty file as an output. What's exactly are you looking for. Please elaborate. Commented Jul 12, 2018 at 16:36
  • lets say i want read 123 from file then i will do other stuffs then want to remove 123 from file and i want to go like that and finally i want empty file as a output Commented Jul 12, 2018 at 16:37
  • 1
    Clear-Content $file? Commented Jul 12, 2018 at 16:53
  • 1
    Why would you delete each line? Just read the file, process it, then clear it. Commented Jul 12, 2018 at 17:00
  • 1
    @Rab The business is wrong. There's no logical reason to do that. Commented Jul 12, 2018 at 17:04

1 Answer 1

1

What you want to do is called "truncating a file". PowerShell has a cmdlet for that:

Clear-Content $source1

If you want to do some processing first: do that first, then clear the file:

Get-Content $source1 | ForEach-Object {
    # do stuff with content of $source1
}

Clear-Content $source1

If there is a situation where you want to process the content and keep lines under one circumstance or the other you could collect the lines that should be kept in a variable and write that back to the file:

$remains = Get-Content $source1 | ForEach-Object {
    if (<# some condition or other #>) {
        # do stuff with matching lines
    } else {
        # output back to pipeline
        $_
    }
}

# write $remains back to file if it's not empty, otherwise clear file
if ($remains) {
    $remains | Set-Content $source1
} else {
    Clear-Content $source1
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.