执行 Start-Process 后,Powershell“忘记”访问 UNC 路径

执行 Start-Process 后,Powershell“忘记”访问 UNC 路径

我的 powershell 脚本中有一个非常奇怪的行为:

$env:SEE_MASK_NOZONECHECKS = 1

$path = "FileSystem::\\some_server\share\Build-Agent-Tools"

# If $path would be a local path, the very last line (UNC access) would never fail
$runtime = "$path\dotnet-runtime-2.2.8-win-x64.exe"

$res = Start-Process -Wait -FilePath $runtime -ArgumentList "/install /passive /norestart" -PassThru


@(Get-ChildItem -Path $path ) # This says $path not found, what?!!

我的做法:我从给定的 UNC 路径中选择一个 dotnet-runtime 安装程序并将其安装在我的机器上。然后,我在选择的运行时可执行文件的同一 UNC 路径上执行 Get-ChildItem,然后出现此错误:

Get-ChildItem : Cannot find path '\\some_server\share\Build-Agent-Tools' because it does not exist.
At D:\Untitled1.ps1:11 char:3
+ @(Get-ChildItem -Path $path ) # This says $path not found, what?!!
+   ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (\\some_server\share\Build-Agent-Tools:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

其他可执行文件不会产生此类问题。此外,从非 UNC路径,然后Get-ChildItem在同一路径上执行上面相同的代码就可以了。

在这种情况下会发生什么?

我还发现插入Start-Sleep 5 Start-Process在失败Get-ChildItem之前有时帮助。有时 5 秒失败,有时 10 秒有效。

这可能是什么问题?

答案1

嗯,这不是一个完整的解决方案,但我添加了一个辅助方法,可以等待路径准备就绪

function Wait-For-Path-Ready($path) {
    echo "Waiting for '$path' be ready"
    $tries = 100
    $waitInMs = 100
    $success = $false

    for ($i = 0; $i -le $tries; ++$i) {
        try {

            Get-ChildItem $path -ErrorAction Stop | Out-Null
            $success = $true
            break;

        }
        catch {
            echo "Path not ready, retrying"
            Start-Sleep -Milliseconds $waitInMs
        }
    }

    if( $success )
    {
        echo "Path is ready"
    }
    else {
        throw "$path failed to become ready after $($tries*$waitInMs / 1000) seconds"
    }

}

用法:

Wait-For-Path-Ready "somepath`

相关内容