You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用System.IO.StreamReader时Set-Content提示文件被占用的问题

问题分析与解决方案

错误原因

你遇到的“文件正被另一进程使用”错误,是因为代码中同时用两种方式操作同一个文件:

  1. 用StreamReader打开文件并保持锁定状态
  2. 循环内又调用Get-Content/Set-Content读写同一文件,导致进程冲突
    另外,foreach ($build in $line)是把字符串拆成单个字符遍历,完全不符合你识别build(行的需求。

核心解决方案

先把文件内容全部加载到内存(或逐行读取到数组),处理完成后再一次性写回文件,避免文件锁定冲突;同时调用自定义函数生成替换值,处理单行/多行的build语句。


实现代码

1. 自定义替换函数(根据Job名生成替换内容)

function Get-ReplacementValue {
    param([string]$JobName)
    # 此处替换为你的实际逻辑,根据JobName返回对应的替换文本
    switch ($JobName) {
        "job1" { return 'build("Job1", parameter1: "newValue1")' }
        "job2" { return 'build("Job2", parameter3: "newValue3", parameter4: "newValue4", parameter5: "newValue5")' }
        "job3" { return 'build("Job3", parameter6: "newValue6", parameter7: "newValue7", parameter8: "newValue8", parameter9: "newValue9")' }
        default { return $_ }
    }
}

2. 处理文件(兼容单行/多行build语句)

# 读取文件所有内容到内存(适合中小文件)
$fileContent = Get-Content -Path "$PSScriptRoot/text.txt" -Raw

# 匹配单行build语句(build(...)在同一行)
$singleLinePattern = 'build\( "([^"]+)", (.+?) \)'
$fileContent = $fileContent -replace $singleLinePattern, {
    $jobName = $args[0].Groups[1].Value
    Get-ReplacementValue -JobName $jobName
}

# 匹配多行build语句(参数换行的情况)
$multiLinePattern = 'build\( "([^"]+)", (.+?)\s+\)'
$fileContent = $fileContent -replace $multiLinePattern, {
    $jobName = $args[0].Groups[1].Value
    Get-ReplacementValue -JobName $jobName
}

# 写回处理后的内容
Set-Content -Path "$PSScriptRoot/text.txt" -Value $fileContent

3. 大文件适配方案(逐行处理,避免内存占用过高)

$lines = Get-Content -Path "$PSScriptRoot/text.txt"
$processedLines = @()
$inBuildBlock = $false
$currentBuildLine = ""

foreach ($line in $lines) {
    if ($line.Contains("build(")) {
        $inBuildBlock = $true
        $currentBuildLine = $line
    } elseif ($inBuildBlock -and $line.Contains(")")) {
        $currentBuildLine += " " + $line.Trim()
        $inBuildBlock = $false
        # 提取Job名并调用替换函数
        $jobName = [regex]::Match($currentBuildLine, 'build\( "([^"]+)"').Groups[1].Value
        $processedLines += Get-ReplacementValue -JobName $jobName
    } elseif ($inBuildBlock) {
        $currentBuildLine += " " + $line.Trim()
    } else {
        $processedLines += $line
    }
}

Set-Content -Path "$PSScriptRoot/text.txt" -Value $processedLines

内容的提问来源于stack exchange,提问作者Hemanth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:52:35