Find and replace in files fails

ぃ、小莉子 提交于 2019-12-04 15:16:21

问题


I am trying to do find and replace in a file using following approach.

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

But i am always getting error.

Set-Content : The process cannot access the file 'c:\program files (x86)\MyProj\web.config' because it is being used by another process.

The file is not opened any where. I think Get-content is yet to release the file.

Why it happens ? How to do find and replace in the same file without issue?


回答1:


You can't read and write to the same file while it's open, Get-Content opens the file for reading and in the same time Set-Content tries to write to it. Put the Get-Conetnt call in parentheses, it will open the file, read it's content and close it.

(Get-Content $FileFullpath) | ...


来源:https://stackoverflow.com/questions/10480673/find-and-replace-in-files-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!