powershell

Set-Content sporadically fails with "Stream was not readable"


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:

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
}

This function will sporadically fail with the error:

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

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?


Solution

  • Sorry, I have no idea why this happens but you could give my Replace-TextInFile function a try. If I remember correctly I had a similar issue using Get-contet as well:

    function Replace-TextInFile
    {
        Param(
            [string]$FilePath,
            [string]$Pattern,
            [string]$Replacement
        )
    
        [System.IO.File]::WriteAllText(
            $FilePath,
            ([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
        )
    }