查找和替换文件失败

Sam*_*abu 27 powershell powershell-2.0

我试图使用以下方法在文件中查找和替换.

Function Find-Replace ($FileFullpath, $FindString, $ReplacementString) {

   Get-Content $FileFullpath | 
   Foreach-Object {$_ -replace $FindString, $ReplacementString } |  
   Set-Content $FileFullpath

}

Find-Replace "c:\program files (x86)\MyProj\web.config" $OldServiceName $NewServiceName
Run Code Online (Sandbox Code Playgroud)

但我总是得到错误.

Set-Content:进程无法访问文件'c:\ program files(x86)\ MyProj\web.config',因为它正由另一个进程使用.

该文件不会在任何地方打开.我认为Get-content尚未发布该文件.

为什么会这样?如何在同一个文件中查找和替换没有问题?

Sha*_*evy 54

在打开时,您无法读取和写入同一文件,Get-Content会打开文件进行读取,同时Set-Content会尝试写入该文件.将Get-Conetnt调用放在括号中,它将打开文件,读取它的内容并关闭它.

(Get-Content $FileFullpath) | ...
Run Code Online (Sandbox Code Playgroud)

  • 我在搜索结果半小时,对失败感到沮丧.我提出这个问题然后去喝咖啡.现在回答就在这里.几个月前发生了同样的事情.引人注目的事情是Levy :) (3认同)
  • 谢谢@Samselvaprabu 很高兴提供帮助。您也可以在帮助中找到此内容:http://technet.microsoft.com/en-us/library/dd347736.aspx,看看第三个示例。 (3认同)