首页 > 解决方案 > Powershell查找和替换失败,因为文件被另一个进程使用

问题描述

在 for 循环中,我在文件中搜索各种模式并用预定义的标记替换它们:

((Get-Content -path $file -Raw) -replace $pattern, $tokenValue) | Set-Content -Path $file

这有时有效,但有时它会因错误而失败:

The process cannot access the file 'my-file' because it is being used by another process.

我看到解决方法是使用管道 | (在文件中查找和替换失败)但我已经这样做了。这个问题的另一个原因是什么?

这是完整的片段:

 foreach ($variable in $variables) {
        $token = $variable.Value.replace("__", "")

        if ([bool]($group.variables.PSobject.Properties.name -eq $token)){
            Write-Host -ForegroundColor DarkGreen "Match found ! token $token"

            $tokenValue = $group.variables | Select-Object -ExpandProperty $token | Select-Object -ExpandProperty Value
            Write-Host -ForegroundColor DarkGreen  "replacing " $variable.Value " with $tokenValue"
          
            ((Get-Content -path $file -Raw)  -replace $pattern, $tokenValue) | Set-Content -Path $file
        }       
    }

标签: powershell

解决方案


推荐阅读