Set-Content sporadically fails with "Stream was not readable" : <p>I have some PowerShell scripts that prepare files before a build. One of the actions is to replace certain text in the files. I use the following simple function to achieve this:</p>

<pre><code>function ReplaceInFile {
    Param(
        [string]$file,
        [string]$searchFor,
        [string]$replaceWith
    )

    Write-Host "- Replacing '$searchFor' with '$replaceWith' in $file"

    (Get-Content $file) |
    Foreach-Object { $_ -replace "$searchFor", "$replaceWith" } |
    Set-Content $file
}
</code></pre>

<p>This function will sporadically fail with the error:</p>

<pre><code>Set-Content : Stream was not readable.
At D:\Workspace\powershell\ReplaceInFile.ps1:27 char:5
+     Set-Content $file
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (D:\Workspace\p...AssemblyInfo.cs:String) [Set-Content], ArgumentException
    + FullyQualifiedErrorId : GetContentWriterArgumentError,Microsoft.PowerShell.Commands.SetContentCommand
</code></pre>

<p>When this happens, the result is an empty file, and an unhappy build. Any ideas why this is happening? What should I be doing differently?</p>
