0

I have this powershell code which should replace every occurrence of a string in every file in the directory with a new string. This works, however an empty line is added in the end. What causes this, and how can this be nicely avoided?

$files = Get-ChildItem $currentDir *.* -recurse
foreach ($file in $files)
    {
    $find = "placeholder"
    $replace = "newvalue"
    $content = Get-Content $($file.FullName) -Raw
    $content -replace $find,$replace | Out-File $($file.FullName) 
    }

Simply removing the last line is not a good solution since sometimes my files will contain an empty line which I want to keep.

Houbie
  • 1,406
  • 1
  • 13
  • 25

2 Answers2

3

You could use the -NoNewline parameter to prevent Out-File from appending the extra line at the end of the file.

$content -replace $find,$replace | Out-File $($file.FullName) -NoNewline

Note: this was added in PowerShell 5.0

BenH
  • 9,766
  • 1
  • 22
  • 35
  • 1
    For prior versions of PowerShell you might consider using `Set-Content` or `Add-Content` but mind the differences with `Out-File`: https://stackoverflow.com/questions/10655788/powershell-set-content-and-out-file-what-is-the-difference – iRon Aug 03 '17 at 18:49
  • I put my version in a comment, so that the formatting looks better. I am still limited to PS version 4. – Houbie Aug 04 '17 at 08:19
0

I am limited to PS version 4, and this is what I used

$files = Get-ChildItem $currentDir . -recurse

$find = "placeholder"
$replace = ""newvalue"    

foreach ($file in $files)
    {
    $content = Get-Content $($file.FullName) -Raw | ForEach-Object { $_ -replace $find,$replace}
    $content = $content -join "`r`n"

    $content | Set-Content  $($file.FullName)      
    }

Note that this only works if it is ok to store the complete file in memory.

Houbie
  • 1,406
  • 1
  • 13
  • 25