gpt4 book ai didi

powershell - 设置内容偶尔失败,错误为 "Stream was not readable"

转载 作者:行者123 更新时间:2023-12-04 03:35:54 24 4
gpt4 key购买 nike

我有一些 PowerShell 脚本可以在构建之前准备文件。其中一项操作是替换文件中的某些文本。我使用以下简单函数来实现这一点:

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
}

此函数偶尔会失败并显示以下错误:
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

发生这种情况时,结果是一个空文件和一个不愉快的构建。任何想法为什么会发生这种情况?我应该怎么做?

最佳答案

抱歉,我不知道为什么会这样,但你可以给我的 Replace-TextInFile
功能一试。如果我没记错的话,我在使用 Get-contet 时遇到了类似的问题。还有:

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

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

关于powershell - 设置内容偶尔失败,错误为 "Stream was not readable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com