Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell替换文件中的内容添加redundent回车符_Powershell - Fatal编程技术网

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

Powershell替换文件中的内容添加redundent回车符,powershell,Powershell,我有以下脚本,应该从cmd脚本运行: powershell -command "(Get-Content %baseKitPathFile%) | ForEach-Object { $_ -replace 'Latest', '%version%' } | Set-Content %baseKitPathFile%" 脚本工作正常,将最新版本的内容替换为版本变量,但它也会在文件结束后添加回车符 如何在没有额外回车的情况下搜索替换文本文件内容 可能正在尝试使用[io.file]: 最重要的是,i

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

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)
解析路径。