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?
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)
)
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With