Powershell获取内容互斥体找不到路径

时间:2019-11-28 00:22:25

标签: powershell

大图是用多个脚本的状态更新json文件,每个更新应花费毫秒,每个脚本总共需要10次更新,但实际上可能同时发生。

我有一个功能,我试图从多个计划任务中更新status.json文件,每个计划任务均从单独的计划任务>批处理文件> PowerShell中执行。我使用互斥锁来获取锁,这样他们就不会为文件争吵。

我的第一个“线程”似乎工作正常,它更新文件没有问题,并继续进行并不断更新。其他“线程”返回Cannot find path 'D:\status.json' because it does not exist.错误。为什么Get-Content会因为第一个“线程”工作而失败,所以文件必须存在是没有道理的。

这可能是错误的错误,也许实际上只是被锁定了。我将如何测试是否已锁定以及为什么不解锁,我尝试了各种睡眠,但错误仍然发生。

有人有什么想法,想法,改进吗?

$PSVersionTable.PSVersion
Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14393  3053    
Function UpdateStatus ([String]$db,[String]$start,[String]$end,[String]$status)
{
    $InFile = "D:\status.json"

    $mtx = New-Object System.Threading.Mutex($false, "Global\LogMutex")
    [void]$mtx.WaitOne()

    Try
    {
        $stsJSON = Get-Content $InFile -Encoding UTF8 -ErrorAction Stop | Out-String | ConvertFrom-Json

        $stsJSON | ForEach-Object `
        {
            If ($_.DatabaseName -eq $db)
            {
                If ($start -ne $null -and $start -ne "")
                {
                    $_.Start = $start
                }

                If ($end -ne $null -and $end -ne "")
                {
                    $_.End = $end
                }

                If ($status -ne $null -and $status -ne "")
                {
                    $_.Status = $status
                }
            }
        }

        $stsJSON | ConvertTo-Json -Depth 100 | Set-Content $InFile -Encoding UTF8
    }
    Catch
    {
        Write-Host "Could not update Status. `r`n"
        Write-Host "`r`n"
        Write-Host "$_`r`n" -ForegroundColor Red
        Start-Sleep 1
    }

    Start-Sleep -Seconds 1
    [void]$mtx.ReleaseMutex()
}

1 个答案:

答案 0 :(得分:0)

虽然我不能确定上面的代码能否100%正常工作,但是我认为我的测试不正确,因此当我收到新要求时,将这种方法放弃了,使用了其他选项。今天的新要求是,实例将在不同的服务器上分开,并且我认为Mutex无法在UNC上运行。我选择尝试使用file.lock方法。