Powershell 替换文件中的内容添加了冗余回车 [英] Powershell replace content in file adds redundent carriage return

查看:66
本文介绍了Powershell 替换文件中的内容添加了冗余回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本应该从 cmd 脚本运行:

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%"

脚本工作正常,将 Latest 的内容替换为 version 变量,但它也在文件末尾添加回车

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

可能正在尝试使用 [io.file]:

最重要的是如果应该从cmd脚本运行

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

推荐答案

Set-ContentOut-File 都在每行之后放置一个换行符,包括最后一行.为了避免这种情况,您必须使用 IO.File 方法:

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)"

PowerShell 脚本比上面的命令行更易于处理:

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)

这样称呼它:

powershell -File "C:\path\to\your.ps1" "%baseKitPathFile%" "%version%"

这篇关于Powershell 替换文件中的内容添加了冗余回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆