在文件中查找和替换失败 [英] Find and replace in files fails
问题描述
我正在尝试使用以下方法在文件中查找和替换.
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
但我总是出错.
Set-Content : 进程无法访问文件 'c:\program files(x86)\MyProj\web.config' 因为它正被另一个进程使用.
Set-Content : The process cannot access the file 'c:\program files (x86)\MyProj\web.config' because it is being used by another process.
文件没有在任何地方打开.我认为 Get-content 尚未发布该文件.
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?
推荐答案
同一个文件打开时不能读写,Get-Content 会打开文件进行读取,同时 Set-Content 会尝试写信给它.将 Get-Conetnt 调用放在括号中,它将打开文件,读取其内容并关闭它.
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) | ...
这篇关于在文件中查找和替换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!