1

I have the following script that should be running from a cmd script:

powershell -command "(Get-Content %baseKitPathFile%) | ForEach-Object { $_ -replace 'Latest', '%version%' } | Set-Content %baseKitPathFile%"

The script is working fine and replacing the content of Latest to a version variable however it also adds carriage return after the end of the file

How can I search replace a text file content without the extra carriage return

maybe be trying to use [io.file]:

The most important is that if should be running from cmd script

user829174
  • 6,132
  • 24
  • 75
  • 125

1 Answers1

0

Set-Content and Out-File both put a linebreak after each line, including the last one. To avoid that you must use an IO.File method:

powershell -Command "$txt = (Get-Content %baseKitPathFile%) -replace 'Latest', '%version%'; [IO.File]::WriteAllText('%baseKitPathFile%', $txt)"

A PowerShell script would be better to handle than the above commandline, though:

[CmdletBinding()]
Param(
  [Parameter()][string]$Filename,
  [Parameter()][string]$Version
)

$txt = (Get-Content $Filename) -replace 'Latest', $Version
[IO.File]::WriteAllText($Filename, $txt)

Call it like this:

powershell -File "C:\path\to\your.ps1" "%baseKitPathFile%" "%version%"
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • The only drawback to this method is that .NET paths and PowerShell paths are often different. For example, while you can pass "~\somefile.txt" to `Set-Content` or `Out-File`, .NET will not understand it. Same with paths based on the current directory or those mapped to PSDrives. To work around this, first resolve the path with `$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Filename)`. – Josh Mar 30 '17 at 20:56