Prevent Powershell Use of Newline at End of File

I needed to replace the HTML objects in files in several subfolders, so I used the PowerShell script suggested here: https://stackoverflow.com/a/316618/

However, that script adds an extra line to the end of the file, and I would like to avoid it. There was another script mentioned in the following comment in this thread ( https://stackoverflow.com/a/166269/ ), which was supposed to achieve exactly what I needed, but that did not work when I tried to run it.

Here is my script:

$configFiles = Get-ChildItem . *.xml -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace '&# 8211;','–' } |
    Foreach-Object { $_ -replace '&# 160;',' ' } |
    Foreach-Object { $_ -replace '&# 8221;','"' } |
    Set-Content $file.PSPath
}

All I have to do is not add a new line to the end.

Thank you in advance!

+4
source share
1

PowerShell v5 + -NoNewline Set-Content ( Add-Content Out-File).

, .NET Framework , , .

Caveat: -NoNewline , , , ( ).
, , -NoNewline , , , , , - :
(('one', 'two', 'three') -join "`n") + "`n" | Set-Content -NoNewLine $filePath).
: .


: ForEach-Object < <28 > ; (PSv3 +, - Get-Content -Raw, -Raw, ( ) PSv2 ):

Get-ChildItem . *.xml -Recurse |
  ForEach-Object { 
    $filePath = $_.FullName 
    (Get-Content -Raw $filePath) -replace '&# 8211;', '–' `
       -replace '&# 160;', ' ' `
          -replace '&# 8221;', '"' |
            Set-Content -NoNewline $filePath
  }

:

TheMadTechnician , $filePath script ForEach-Object -PipelineVariable (-pv):

Get-ChildItem . *.xml -Recurse -PipelineVariable ThisFile |
  ForEach-Object { 
    (Get-Content -Raw $ThisFile.FullName) -replace '&# 8211;', '–' `
       -replace '&# 160;', ' ' `
          -replace '&# 8221;', '"' |
            Set-Content -NoNewline $ThisFile.FullName
  }

, , PipelinVariable, $, .
$ThisFile Get-ChildItem (-) .

, -PipelinVariable , , , .

+7

Source: https://habr.com/ru/post/1674788/


All Articles