I am trying to do something very simple in PowerShell.
- Reading the contents of a file
- Manipulation some string
-
Saving the modified test back to the file
function Replace { $file = Get-Content C:\Path\File.cs $file | foreach {$_ -replace "document.getElementById", "$"} |out-file -filepath C:\Path\File.cs }
I have tried Set-Content as well.
I always get unauthorized exception. I can see the $file has the file content, error is coming while writing the file.
How can I fix this?
This is likely caused by the
Get-Contentcmdlet that gets a lock for reading andOut-Filethat tries to get its lock for writing. Similar question is here: Powershell: how do you read & write I/O within one pipeline?So the solution would be:
Basically you need to buffer the content of the file so that the file can be closed (
Get-Contentfor reading) and after that the buffer should be flushed to the file (Set-Content, during that write lock will be required).