Powershell替换文件中的内容添加了redundent回车

时间:2015-06-10 08:43:05

标签: powershell

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

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

脚本工作正常并将Latest的内容替换为version变量,但它也会在文件结束后添加回车符

如何在没有额外回车的情况下搜索替换文本文件内容

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

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

1 个答案:

答案 0 :(得分:0)

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

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

但是,PowerShell脚本比上面的命令行更好处理:

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