Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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?

like image 553
danBhentschel Avatar asked Feb 23 '18 18:02

danBhentschel


2 Answers

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)
    )
}
like image 55
Martin Brandl Avatar answered Sep 21 '22 07:09

Martin Brandl


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!

like image 41
Chad Avatar answered Sep 21 '22 07:09

Chad