Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell查找和替换失败,因为另一个进程正在使用该文件_Powershell - Fatal编程技术网

Powershell查找和替换失败,因为另一个进程正在使用该文件

Powershell查找和替换失败,因为另一个进程正在使用该文件,powershell,Powershell,在for循环中,我搜索文件中的各种模式,并用预定义的标记替换它们: ((获取内容-路径$file-原始)-替换$pattern,$tokenValue)|设置内容-路径$file 这有时有效,但有时会出现错误: 进程无法访问文件“我的文件”,因为另一进程正在使用该文件。 我知道解决这个问题的办法是使用管道,但我已经在做了。这个问题的另一个原因是什么 以下是完整的片段: foreach ($variable in $variables) { $token = $variable.

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

((获取内容-路径$file-原始)-替换$pattern,$tokenValue)|设置内容-路径$file

这有时有效,但有时会出现错误:

进程无法访问文件“我的文件”,因为另一进程正在使用该文件。

我知道解决这个问题的办法是使用管道,但我已经在做了。这个问题的另一个原因是什么

以下是完整的片段:

 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
        }       
    }

您是否在其他应用程序中打开了该文件?否该文件由脚本创建,除脚本本身外,其他任何进程均未使用该文件。我将尝试@AdminOfThings suggestionTry
$content=((获取内容-路径$file-Raw)-替换$pattern,$tokenValue)
设置内容-路径$file-值$content
,而不是使用pipe@AdminOfThings这个建议也有同样的错误。我现在正在尝试Adis1102建议。为什么还要多次写入同一个文件?只需更新内存中的内容,并在最后写入文件
$content=Get content-path$file-Raw在循环之前。然后在循环过程中使用
$content=$content-替换$pattern,$tokenValue
更新
$content
。然后在循环之后,更新文件
$content | set content$file