PowerShell Lock File

I am trying to do something very simple in PowerShell.

  • Reading file contents
  • Some string manipulation
  • Saving the modified test back to file

    function Replace { $file = Get-Content C:\Path\File.cs $file | foreach {$_ -replace "document.getElementById", "$"} |out-file -filepath C:\Path\File.cs } 

I tried Set-Content .

I always get an unauthorized exception. I see that $file has the contents of the file, an error occurs while writing the file.

How can i fix this?

+6
powershell
source share
2 answers

This is probably caused by the Get-Content cmdlet, which gets a read lock and Out-File , which tries to get its write lock. A similar question: Powershell: how do you read and write I / O in one pipeline?

So the solution would be:

 ${C:\Path\File.cs} = ${C:\Path\File.cs} | foreach {$_ -replace "document.getElementById", '$'} ${C:\Path\File.cs} = Get-Content C:\Path\File.cs | foreach {$_ -replace "document.getElementById", '$'} $content = Get-Content C:\Path\File.cs | foreach {$_ -replace "document.getElementById", '$'} $content | Set-Content C:\Path\File.cs 

Basically, you need to buffer the contents of the file so that the file can be closed ( Get-Content for reading), and after that the buffer should be flushed to the file ( Set-Content , during which write lock is required).

+4
source share

The accepted answer worked for me if I had one file operation, but when I performed several Set-Content or Add-Content operations for the same file, I still got the error β€œis being used by another process”.

In the end, I had to write a temporary file, and then copy the temporary file to the source file:

 (Get-Content C:\Path\File.cs) | foreach {$_ -replace "document.getElementById", '$'} | Set-Content C:\Path\File.cs.temp Copy-Item C:\Path\File.cs.temp C:\Path\File.cs 
0
source share

All Articles