Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - 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)MyProjweb.config" $OldServiceName $NewServiceName

But i am always getting error.

Set-Content : The process cannot access the file 'c:program files (x86)MyProjweb.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) | ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...