PowerShell locking File

This is likely caused by the Get-Content cmdlet that gets a lock for reading and Out-File that 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:

${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 content 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 that write lock will be required).

Tags:

Powershell