1

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.

2
  • All files are in Unicode? Commented Aug 3, 2017 at 15:54
  • 3
    It's out-file that adds a newline, not -replace Commented Aug 3, 2017 at 16:05

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

For prior versions of PowerShell you might consider using Set-Content or Add-Content but mind the differences with Out-File: stackoverflow.com/questions/10655788/…
I put my version in a comment, so that the formatting looks better. I am still limited to PS version 4.
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.

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.