Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.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
File Powershell脚本,用于使用保留换行符的不同文本文件中的内容替换字符串_File_Powershell_Replace - Fatal编程技术网

File Powershell脚本,用于使用保留换行符的不同文本文件中的内容替换字符串

File Powershell脚本,用于使用保留换行符的不同文本文件中的内容替换字符串,file,powershell,replace,File,Powershell,Replace,我必须用不同文件中的内容替换文件中的字符串,但我需要保留换行符。原始文件在插入点前后都有文本 我正在尝试使用以下代码执行此操作: $v_notes = Get-Content -path $cp_file_temp_rep $file = Get-Content -path $ip_file_template | ForEach-Object { $line2 = $_ $line2 -replace "placenoteshere", $v_notes | } Set-Content

我必须用不同文件中的内容替换文件中的字符串,但我需要保留换行符。原始文件在插入点前后都有文本

我正在尝试使用以下代码执行此操作:

$v_notes = Get-Content -path $cp_file_temp_rep
$file = Get-Content -path $ip_file_template |
ForEach-Object {
  $line2 = $_
  $line2 -replace "placenoteshere", $v_notes |
} 
Set-Content -Path $op_file_replaced -value $file

也许将
$v_notes
中的行添加到
$file
中是可行的,但我不知道如何实现这一点。

获取内容
默认为逐行处理文件。如果文件不大,您可能会发现将整个文件以字符串形式读入会更容易,例如:

$v_notes = Get-Content $cp_file_temp_rep -raw
$file = Get-Content $ip_file_template -raw
$file = $file -replace "placenoteshere",$v_notes
$file | Out-File $ip_file_template -Encoding ascii
将文件内容写回时使用适当的编码。PowerShell中Out文件的默认值为Unicode

如果您在v1/v2上:

$v_notes = [IO.File]::ReadAllText($cp_file_temp_rep)
$file = [IO.File]::ReadAllText($ip_file_template)
$file = $file -replace "placenoteshere",$v_notes
$file | Out-File $ip_file_template -Encoding ascii

请注意,需要路径的.NET方法调用将需要完整路径。

您好,很遗憾这不起作用,对我来说:获取内容:找不到与参数名称“raw”匹配的参数。您使用的是哪个版本的PowerShell?原始参数在v3中引入,当前版本为v4.;-)也就是说,在v1/v2中,您可以很容易地解决这个问题。我会更新我的答案非常感谢!这很有效!我只是需要修改一下打字错误再次感谢@用户3245349对此表示抱歉。我想我都修好了。