locked
Out-File not overwriting RRS feed

  • Question

  • I wrote a simple script, that searches through the files for a certain string and writes those matched lines into a new file. Why doesn't it overwrite the file when I execute the script again? In documentation says that Out-File overwrites existing file by default. In my case it only adds same lines to the output file. What am I missing?

    This is the script:

    $FilePath = 'E:\test'
    $files = Get-ChildItem $FilePath\*.txt
    $rezultat = @()
    
    foreach ($file in $files) {
         $rezultat+= Get-Content $file | Select-String $string -Context 0 -SimpleMatch
    }
    
    $rezultat | Out-File E:\test\rezultat.txt


    • Moved by Bill_Stewart Thursday, January 3, 2019 3:54 PM Abandoned
    Sunday, November 4, 2018 10:08 PM

All replies

  • I think you analysis is wrong.  "Out-File" always over-writes a file.

    To do this with PowerShell you would just doo the following:

    $FilePath = 'E:\test'
    Select-String -Path $FilePath\*.txt $string -Context 0 -SimpleMatch | Out-File E:\test\rezultat.txt


    \_(ツ)_/


    • Edited by jrv Sunday, November 4, 2018 10:35 PM
    Sunday, November 4, 2018 10:35 PM