Powershell替换文件中的内容添加redundent回车符
我有以下脚本,应该从cmd脚本运行:Powershell替换文件中的内容添加redundent回车符,powershell,Powershell,我有以下脚本,应该从cmd脚本运行: powershell -command "(Get-Content %baseKitPathFile%) | ForEach-Object { $_ -replace 'Latest', '%version%' } | Set-Content %baseKitPathFile%" 脚本工作正常,将最新版本的内容替换为版本变量,但它也会在文件结束后添加回车符 如何在没有额外回车的情况下搜索替换文本文件内容 可能正在尝试使用[io.file]: 最重要的是,i
powershell -command "(Get-Content %baseKitPathFile%) | ForEach-Object { $_ -replace 'Latest', '%version%' } | Set-Content %baseKitPathFile%"
脚本工作正常,将最新版本的内容替换为版本
变量,但它也会在文件结束后添加回车符
如何在没有额外回车的情况下搜索替换文本文件内容
可能正在尝试使用[io.file]:
最重要的是,if应该从cmd脚本运行,设置内容和输出文件都在每一行后面放一个换行符,包括最后一行。为了避免这种情况,必须使用IO.File
方法:
powershell -Command "$txt = (Get-Content %baseKitPathFile%) -replace 'Latest', '%version%'; [IO.File]::WriteAllText('%baseKitPathFile%', $txt)"
PowerShell脚本比上述命令行更易于处理,不过:
[CmdletBinding()]
Param(
[参数()][string]$Filename,
[参数()][字符串]$Version
)
$txt=(获取内容$Filename)-替换为“最新”、$Version
[IO.File]::writealText($Filename,$txt)
可以这样称呼:
powershell -File "C:\path\to\your.ps1" "%baseKitPathFile%" "%version%"
将设置内容
替换为输出文件
不工作,仍然添加额外的行此方法的唯一缺点是.NET路径和PowerShell路径通常不同。例如,虽然您可以将“~\somefile.txt”传递给设置内容
或输出文件
,但.NET不会理解它。与基于当前目录的路径或映射到PSDrives的路径相同。要解决此问题,请首先使用$ExecutionContext.SessionState.path.getUnsolvedProviderPathFrompPath($Filename)
解析路径。