查找和替换文件失败(Find and replace in files fails)

2019-07-29 06:48发布

我想已经找到并使用以下方法在文件中替换。

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

但我总是得到错误。

因为它正被其他进程设置内容:该进程无法访问该文件“\程序文件(x86)\的Myproj \ web.config中C”。

在不打开文件的任何地方。 我想获取内容是尚未发布的文件。

为什么会发生? 怎么办查找并在同一个文件替换没有问题?

Answer 1:

你不能读取和写入到同一个文件,而它的开放,获取内容打开文件进行读取,并在同一时间设置内容试图写它。 放在括号中的Get-Conetnt调用,它会打开文件,读取它的内容并关闭它。

(Get-Content $FileFullpath) | ...


文章来源: Find and replace in files fails