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

I ran into this and it turned out to be that the files I was trying to change were part of a solution that was open in Visual Studio. Closing Visual Studio before running fixed the problem!


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)
    )
}

As mentioned by joelsand there's a slight improvement that can be made to Martin Brandl's answer.

function Replace-TextInFile
{
    Param(
        [string]$FilePath,
        [string]$Pattern,
        [string]$Replacement, 
        [System.Text.Encoding] $Encoding
    )

    if($Encoding) {
        [System.IO.File]::WriteAllText(
            $FilePath,
            ([System.IO.File]::ReadAllText($FilePath, $Encoding) -replace $Pattern, $Replacement),
            $Encoding
        )
    } else { 
        [System.IO.File]::WriteAllText(
            $FilePath,
            ([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
        )
    }
}

Example:

$encoding = [System.Text.Encoding]::UTF8
Replace-TextInFile -FilePath $fullPath -Pattern $pattern -Replacement $replacement -Encoding $encoding

Tags:

Powershell